$(function () {
	 
  //全局变量保存新增用例的id
  var addBaseCaseId="";
  currentAddBaseCaseId = "";//当前basecaseid
  baseCaseEditeBool = true;//当前是否可以编辑
  baseCaseData =[];//基本用例基础信息
  caseElements = [];// 保存画布上所有的用例元素
  elementTypes=[];// 保存画布上所有的用例元素类型
  elementData = [];//初始化用例元素对象为空
  currentObj = {};//当前左侧选中元素要拖入画布
  caseElementValId =""; //条件组合ID 
  selectx1 = 0;//画布中选中元素的限定区域x1
  selectx2 = 0;//画布中选中元素的限定区域x2
  var windowWidth = window.innerWidth;
  var centerWidth = windowWidth-566;
  canvase_width = 1500-95;//画布宽度，默认值8888
  $("#canvasDiv").width(centerWidth - 114+20);
  $("#canvasId").width(canvase_width);
  mycanvas = $("#canvasId")[0];//右侧画布画底图
  mycanvas.height=750;
  mycanvas.width=canvase_width;
  context = mycanvas.getContext('2d');//获取画布
  tDrawCanvas = new TDrawCanvas(mycanvas);
  
  mycanvasCopy = $("#canvasIdCopy")[0];//右侧画布画底图
  contextCopy = mycanvasCopy.getContext('2d');//获取画布
  tDrawCanvasCopy = new TDrawCanvas(mycanvasCopy);
  
  stroke = '#000000';
  selectObj = [];//选中的对象
  copyObj = [];//复制时的赋值
  copyObjPostion = null;//复制时的选中坐标
  currentCanvas = mycanvas;
  clickBool = true;//是否可以操作，当复制控件时，如果控件没有复制完成，那么就不能操作
  firstGetCanvaseWidth = false;//获取绘图的初始值
  taskState = 0;//当前任务的状态参数
  andorVal = "";//检查点选中关系
  selectConditionIndex = 0;//当前选择的条件轴
  currentConditionIndex = -1;//记录历史选中的条件轴
  conditions = null;//条件轴的右侧属性数据对象
  currentWdith = 0;//当前选中条件轴的历史宽度
  //设置画布宽度
 // 从用例界面的链接路径中截取ID
var url = location.search; //获取url中"?"符后的字串
     if (url.indexOf("?") != -1) {   
        var str = url.substr(1);   
        strs = str.split("&");   
        addBaseCaseId = strs[0].split('=')[1];
     }  
     currentAddBaseCaseId = addBaseCaseId;
     taskState = 0;
     if(strs.length>=2){
    	 taskState = Number(strs[1].split('=')[1]);
     }
     //角色拥有按钮权限
	 initButton(taskState);
   // 通过ID获取到新增的用例信息
   getBaseCaseByCaseId(addBaseCaseId); //获取基本信息;
//获取用例元素类型
   getElementTypes(addBaseCaseId,mycanvas);
   showBaseCaseTree(mycanvas,elementTypes);
   showLeftElement();
   /*左侧菜单手风琴效果展开*/
   accordion();
//注册编辑保存按钮事件
 $("#edite")[0].onclick=function(){
	 reDrawCheckPoint(caseElements, elementTypes, mycanvas);
	 baseCaseSave(addBaseCaseId,caseElements); 
	 };
// 点击基本信息按钮，展示新建用例的基本信息              
 $("#basicInformation").click(function(){showBaseCaseInfo(baseCaseData);});   
//注册用例的基本信息审核事件            
 $("#Audit").click(function(){auditBaseCase(addBaseCaseId);}); 
 //注册提交基本用例事件
 $("#submit").click(function(){submitBaseCase(addBaseCaseId);});   
      //元素拖拽移动过程中触发事件控制可拖拽的区域
 mycanvas.ondragover = function(ev){
	 if(!baseCaseEditeBool){
			return;
		}
	 //当拖拽到条件轴的上方时，当前条件轴自动设置为选中状态
	 var p = getEventPosition(ev);
	 canvasConditionClick(p, caseElements, elementTypes, mycanvas);
	 getSelectElements(caseElements);
	 dragover(ev, elementTypes);
 };
 mycanvas.ondrop = function(ev){
	 	if(!baseCaseEditeBool){
			return;
		}
          var x = ev.offsetX;
          var y = ev.offsetY; 
          ev.preventDefault();
            var elementId = ev.dataTransfer.getData("elementid");
            var type = ev.dataTransfer.getData("type"); 
            var leve =  ev.dataTransfer.getData("leve");
            var elementType = getElementType(type,elementTypes);
            if(leve=="1"){//元素大类1：基本元素，
              x=selectx1+90*Math.floor((x-selectx1)/90)+10;
              y=elementType.y1+5;//图形放下后的位置进行调整
            }else if(leve=="3"){//元素大类3图形元素
                y = 660;
            }
            getCaseElementInstance(mycanvas,elementId,x,y,caseElements,elementTypes);//绘制元素和图形的方法
          };
       //注册画布元素点击事件
 mycanvas.onmousedown = function(e){ 
		// 当前点击位置的坐标
		var p = getEventPosition(e);
		saves();
		canvasConditionClick(p, caseElements, elementTypes, mycanvas);
		getSelectElements(caseElements);
		canvasClick(p, caseElements, elementTypes, mycanvas);
	};
	// 注册画布元素移动事件
	mycanvas.onmousemove = function(e) {
		if(!baseCaseEditeBool){
			return;
		}
		dragElement(e, caseElements, elementTypes);
	};
	// 根据当前点击点的坐标获取点击的元素并设置选中
	// 画布内元素的清空和删除功能
	$("#emptyElements").click(function() {
		// 清空元素
		emptyElements(mycanvas);
	});
	$("#deleteElements").click(function() {
		deleteElements(mycanvas, caseElements);
	});
	window.onresize = function() {
		var windowWidth = window.innerWidth;
		var centerWidth = windowWidth - 566;
		$("#canvasDiv").width(centerWidth-114+20);
	};
	
	//滚动滚动条，动态改变绘图的大小
	$('#canvasDiv').on('scroll', function(e) {
        if ($(this).scrollLeft() === 0) {
        }
        if (($(this).width() + $(this).scrollLeft()) >= $('#canvasId').width()-96) {
            canvase_width = canvase_width+10;
            $("#canvasId").width(canvase_width);
            mycanvas.height=700;
            mycanvas.width=canvase_width;
            draw(mycanvas, elementTypes, caseElements);
        }
    });
	//鼠标右键功能
	contextmenu();
});

//鼠标右键功能
function contextmenu(){
	if(!baseCaseEditeBool){
		return;
	}
	//自定义鼠标右键菜单
	var onClick = function(e) {
		var clicked = function(e) {
				console.log(e.target.textContent);
				var type = 0;//0：左侧添加，1：右侧添加
				if(e.target.textContent != '左侧添加条件轴'){
					type = 1;
				}
				setNewConditionPosition(type);

				return false;
			};
		var items = [
			{ title: '左侧添加条件轴',  fn: clicked ,id:111},
			{ title: '右侧添加条件轴',  fn: clicked ,id:222}
		];
		
		// 当前点击位置的坐标
		var p = getEventPosition(e);
		currentConditionIndex = -1;
		saves();
		canvasClick(p, caseElements, elementTypes, mycanvas);
		var selections = getSelectElements(caseElements);
		//当点击条件轴下面的小矩形时，可以添加条件轴
		if(selections.length == 1 && !smallRectBool){
			basicContext.show(items, e);
		}
		
		//判断鼠标右键是条件轴内的小矩形
		var clicked2 = function(e) {
			console.log(e.target.textContent);
			var type = 0;//0：左侧添加，1：右侧添加
			if(e.target.textContent != '左侧添加一列'){
				type = 1;
			}
			setNewRowPosition(type,selection2,selections);
			
			return false;
		};
		var items2 = [
		 			{ title: '左侧添加一列',  fn: clicked2 ,id:111},
		 			{ title: '右侧添加一列',  fn: clicked2 ,id:222}
		 		];
		var smallRectBool = false;
		for(var i = 0;i<caseElements.length;i++){
			for(var j = 0;j<caseElements[i].children.length;j++){
				if(caseElements[i].children[j].isSelected){
					smallRectBool = true;
				}
			}
		}
		var p = getEventPosition(e);
		var selection2 = getSelectionElementByPoint(p, caseElements, elementTypes,mycanvas);
		if(smallRectBool){
			basicContext.show(items2, e);
		}
		
		return false;
	};
	
	document.getElementById('canvasId').oncontextmenu = onClick;
	document.body.onselectstart = function(){
		return false;
	};
}
// 清空画布中的元素
function emptyElements(canvas) {
	resetMsg();
	var context = canvas.getContext('2d');
	// 清空画布内的所有元素
	context.clearRect(0, 0, canvase_width, canvas.height);
	// 绘制坐标轴和直线
	drawDashLine(canvas, elementTypes);
	// 直接清空原始数组即可
	caseElements.splice(0, caseElements.length);
}

// 画坐标轴线
function drawDashLine(canvas, elementTypes) {
	var coordinate = tDrawCanvas.getDrawing('coordinate', {
		elementTypes : elementTypes,
		hPoint : {
			x1 : 0,
			y1 : 660,
			x2 : canvas.width,
			y2 : 660
		},
		vPoint : {
			x1 : 95,
			y1 : 0,
			x2 : 95,
			y2 : 750
		},
		dashPoint : {
			x1 : 10,
			y1 : (150),
			x2 : canvase_width,
			y2 : (150)
		},
		dashSpace : 40,color:'#817471'
	});
	coordinate.draw();
}

// 删除当前选中的单个元素
function deleteElements(canvas, caseElements) {
	// 获取选中元素下标
	var selections = getSelectElements(caseElements);
	var index = -1;
	var index1 = -1;
	var index2 = -1;
	if (selections.length == 1) {
		index = selections[0];
		caseElements.splice(index, 1);// 删除选中的元素
		// 更新元素顺序
		for (var i = 0; i < caseElements.length; i++) {
			caseElements[i].displayOrder = i + 1;
		}
		currentConditionIndex = -1;
	} else if (selections.length == 2) {
		// 拿到被选中元素的下标
		index1 = selections[0];
		index2 = selections[1];
		caseElements[index1].children.splice(index2, 1);
		// 更新元素顺序
		for (var j = index2; j < caseElements[index1].children.length; j++) {
			caseElements[index1].children[j].displayOrder = j + 1;
		}
	}
	draw(canvas, elementTypes, caseElements);
	resetMsg();
}
//在canvas内绘制caseElements元素  value是回显的文本
function draw(canvas, elementTypes, caseElements) {
	// 清空画布内的内容
	var context = canvas.getContext('2d');
	context.clearRect(0, 0, canvase_width, canvas.height);
	contextCopy.clearRect(0, 0, mycanvasCopy.width, mycanvasCopy.height);
	// 绘制坐标轴和直线
	var coordinate = tDrawCanvas.getDrawing('coordinate', {elementTypes:elementTypes,
		  hPoint:{x1:0,y1:660,x2:canvase_width,y2:660},
		  vPoint:{x1:95,y1:0,x2:95,y2:750},
		  dashPoint:{x1:10,y1:(150),x2:canvase_width,y2:(150)},
		  dashSpace:40,color:'#817471'});
	  coordinate.draw();
	  
	  var coordinateCopy = tDrawCanvasCopy.getDrawing('coordinateLeft', {elementTypes:elementTypes,
		  hPoint:{x1:0,y1:660,x2:900,y2:660},
		  vPoint:{x1:95,y1:0,x2:95,y2:750}, 
		  dashPoint:{x1:0,y1:(110),x2:900,y2:(110)}, 
		  dashSpace:40,color:'#817471'});
	  coordinateCopy.draw();
	  
	  stroke = '#6c615f';
	// 重新绘制条件轴图形
	if (caseElements) {
		for (var i = 0; i < caseElements.length; i++) {
			var isShow = false;
			//根据后台的数据判断是否有信号机
			for(var p = 0;p<caseElements[i].data.length;p++){
				if(caseElements[i].data[p].name =="011001007"){
					if(caseElements[i].data[p].value && caseElements[i].data[p].value!="" 
						&& caseElements[i].data[p].value!=null && caseElements[i].data[p].value!="-1"&&caseElements[i].data[p].value!="null"){
						isShow = true;
						caseElements[i].signalBool = true;
						caseElements[i].signalName = caseElements[i].data[p].value;
					}
				}
			}
			//根据前台的输入框判断是否有信号机
			if(caseElements[i].signalBool && caseElements[i].signalBool){
				isShow = true;
			}
			if (caseElements[i].type == "011") {
				var conditionArea = tDrawCanvas.getDrawing('conditionArea',{obj:caseElements[i],elementTypes:elementTypes,
					conditionState:caseElements[i].conditionState,signalObj:{x:caseElements[i].x + caseElements[i].width - 40,isShow:isShow}});//条件轴的状态
				conditionArea.draw();
			} else if (caseElements[i].type == "012") {
				var signal = tDrawCanvas.getDrawing('signal', {obj:caseElements[i],color:'#D6D6D4'});
				signal.draw();
			} else if (caseElements[i].type == "013") {
				var graph = tDrawCanvas.getDrawing('graph');
				graph.draw();
			} else if (caseElements[i].type == "014") {
				var kvalueMap = tDrawCanvas.getDrawing('kvalueMap', {
					obj : caseElements[i]
				});
				kvalueMap.draw();
			}
		}
	}
}

//条件轴和检查点的状态改变，根据id查询哪个条件轴或者检查点改变，type:0:条件轴，1：检查点
function updateByConditionState(type,id,state){
	for(var i=0;i<caseElements.length;i++){
		if(type == 0){//条件轴
			if(id == caseElements[i].id){
				caseElements[i].conditionState = state;
				break;
			}
		}else if(type == 1){//检查点
			for(var j= 0;j<caseElements[i].children.length;j++){
				if(caseElements[i].children[j].id == id){//检查点状态
					caseElements[i].children[j].state = state;
					break;
				}
			}
		}
	}
}

//根据当前坐标点返回选中的元素
function getSelectionElementByPoint(p, caseElements, elementTypes,mycanvas) {
	var selection = [];
	if (caseElements) {
		for (var i = 0; i < caseElements.length; i++) {// 图形区域选中
			var childrens = caseElements[i].children;
			var type = caseElements[i].type;
			var x = caseElements[i].x;
			var y = caseElements[i].y;
			caseElements[i].selectArea = -1;
			if (type == "012") {
				// 判断距离圆心（x,580）的距离小于半径20
				var calX = p.x - x;
				var calY = p.y - 580;
				if (Math.pow((calX * calX + calY * calY), 0.5) <= 20) {
					caseElements[i].isSelected = true;
					selection.push(caseElements[i]);
				} else {
					caseElements[i].isSelected = false;
				}
			} else if (type == "014") {
				// 判断选中区域在矩形框中时为选中
				if (p.x < x + 35 && p.x >= x - 35 && p.y >= 570 && p.y <= 600) {
					caseElements[i].isSelected = true;
					selection.push(caseElements[i]);
				} else {
					caseElements[i].isSelected = false;
				}
			} else if (type == "011") {
				// 条件轴选中区域：0、改变条件轴位置；1、选中右边线，可拉宽条件轴；2、点击三角区域，切换折叠条件轴显示
				var objWidth = caseElements[i].width;
				// 条件轴限定区域的可拖拽区域判定l
				var xs1 = (caseElements[i].x - 20) + (objWidth - 10);
				var xs2 = (caseElements[i].x - 20) + objWidth;
				var ys1 = 110;
				var ys2 = elementTypes[elementTypes.length - 1].y2;
				if (p.x >= x - 40 && p.y <= y && p.x <= x && p.y >= y - 20) {// 点击下面小矩形区域
																				// 改变条件轴位置
					caseElements[i].isSelected = true;
					caseElements[i].selectArea = 1;
					selection.push(caseElements[i]);
				} else if (p.x >= (x - 40) && p.x <= x && p.y > 90
						&& p.y <= 110) {
					// 三角形点击效果，三角形变成绿色，折叠矩形区域
					caseElements[i].isSelected = true;
					caseElements[i].selectArea = 2;
					selection.push(caseElements[i]);
				} else if (p.x >= xs1 && p.x <= xs2 && p.y >= ys1 && p.y <= ys2) {// 改变条件轴限定区域
					caseElements[i].isSelected = true;
					caseElements[i].selectArea = 0;
					selection.push(caseElements[i]);
				} else {
					caseElements[i].isSelected = false;
				}
				if (childrens) {
					// 矩形操作
					for (var j = 0; j < childrens.length; j++) { // 小矩形图形选中
						var x = childrens[j].x;
						var y = childrens[j].y;
						var width = childrens[j].width;
						var height = childrens[j].hight;
						// 当点击的位置正好是元素的x1,x2,y1,y2之间时，让小矩形元素可拖拽
						if (p.x >= x && p.y >= y && p.x <= (x + width)
								&& p.y <= y + height) {
							caseElements[i].children[j].color = "rgba(17, 241, 11, 0.94)";// 让点击的小矩形边框变成绿色
							caseElements[i].children[j].fontcolor = "#000000";// 选中矩形的字体变成黑色
							draw(mycanvas, elementTypes, caseElements);// 重绘画布
							caseElements[i].children[j].isSelected = true;
							selection.push(caseElements[i].children[j]);
						} else {
							caseElements[i].children[j].color = "#0F0F0F";// 矩形恢复原来的颜色
							caseElements[i].children[j].fontcolor = "#00AAAA";// 字体恢复颜色
							draw(mycanvas, elementTypes, caseElements);// 重绘画布
							caseElements[i].children[j].isSelected = false;
						}
					}

				}
			}
		}
	}
	return selection;
}

//根据当前坐标点返回选中的元素
function getSelectionConditionByPoint(p, caseElements, elementTypes,mycanvas) {
	var selection = [];
	if (caseElements) {
		for (var i = 0; i < caseElements.length; i++) {// 图形区域选中
			var type = caseElements[i].type;
			var x = caseElements[i].x;
			var y = caseElements[i].y;
			caseElements[i].selectArea = -1;
			if (type == "012") {
				// 判断距离圆心（x,580）的距离小于半径20
				var calX = p.x - x;
				var calY = p.y - 580;
				if (Math.pow((calX * calX + calY * calY), 0.5) <= 20) {
					caseElements[i].isSelected = true;
					selection.push(caseElements[i]);
				} else {
					caseElements[i].isSelected = false;
				}
			} else if (type == "014") {
				// 判断选中区域在矩形框中时为选中
				if (p.x < x + 35 && p.x >= x - 35 && p.y >= 570 && p.y <= 600) {
					caseElements[i].isSelected = true;
					selection.push(caseElements[i]);
				} else {
					caseElements[i].isSelected = false;
				}
			} else if (type == "011") {
				// 条件轴选中区域：0、改变条件轴位置；1、选中右边线，可拉宽条件轴；2、点击三角区域，切换折叠条件轴显示
				var objWidth = caseElements[i].width;
				// 条件轴限定区域的可拖拽区域判定l
				var xs1 = (caseElements[i].x - 20);
				var xs2 = (caseElements[i].x - 20) + objWidth;
				var ys1 = 110;
				var ys2 = elementTypes[elementTypes.length - 1].y2;
				if (p.x >= xs1 && p.x <= xs2 && p.y >= ys1 && p.y <= ys2) {// 改变条件轴限定区域
					caseElements[i].isSelected = true;
					caseElements[i].selectArea = 0;
					selection.push(caseElements[i]);
					selectConditionIndex = i;
				} else {
					caseElements[i].isSelected = false;
				}
			}
		}
	}
	return selection;
}

//重绘检查点
function reDrawCheckPoint(caseElements, elementTypes, canvas){
	for (var i = 0; i < caseElements.length; i++) {
		var childrens = caseElements[i].children;
		for (var j = 0; j < childrens.length; j++) {
			if (childrens[j].type=='009') {
				var p = {
						x:childrens[j].x,
						y:childrens[j].y
				};
				saves();
				canvasClick(p, caseElements, elementTypes,
						canvas);
			}
		}
	}
}
// 点击画布方法p:点击画布坐标位置
function canvasClick(p, caseElements, elementTypes, mycanvas) {
	var id = "";
	// 根据当前点击点的坐标获取点击的元素并设置选中
	var selection = getSelectionElementByPoint(p, caseElements, elementTypes,
			mycanvas);
	for (var i = 0; i < selection.length; i++) {
		id = selection[i].id;// 点击的元素的id
	}
	if (selection.length > 0) {
		$("#caseNamee").empty();
		$("#elementContents").empty();
		$('#conDescription').empty(); // 清空控件说明描述内容
		$('#outParameter').empty();// 清空外部参数内容
		var selectElement = "";
		if (selection[0].isSelected) {
			selectElement = selection[0];
		}
		$('#controlDescription').css('display','block');
		$('#shuxingContent').css('display','block');
		$('#controlDescription').css('display','block');
		var description = selectElement.description;// 控件描述内容获取
		$("#caseNamee").append(
				"<div id='elementName'>元素名称:<span class='backblock' id=" + id
						+ ">" + selectElement.text + "</span></div>");// 元素名称内容插入
		$("#conDescription").append(
				"<div id='controlDescription2'>" + description + "</div>");// 描述内容插入到标签
		showAttribute(selectElement, caseElements);
	}
	rightParameter();// 根据用户权限判断让右侧的参数修改和不可修改
	//点击选中的元素对象
	selectObj = [];
	selectObj.push(selection[0]);//点击的元素对象
	copyObjPostion = p;
	changeElementColor(selection,mycanvas);//被点击的元素突出显示
}


//点击画布方法p:点击画布坐标位置
function canvasConditionClick(p, caseElements, elementTypes, mycanvas) {
	var id = "";
	// 根据当前点击点的坐标获取点击的元素并设置选中
	var selection = getSelectionConditionByPoint(p, caseElements, elementTypes,
			mycanvas);
	//如果已经选定当前条件轴，那么不用重复选中
	if(currentConditionIndex == selectConditionIndex){
		return;
	}
	
	currentConditionIndex = selectConditionIndex;
	for (var i = 0; i < selection.length; i++) {
		id = selection[i].id;// 点击的元素的id
	}
	if (selection.length > 0) {
		$("#caseNamee").empty();
		$("#elementContents").empty();
		$('#conDescription').empty(); // 清空控件说明描述内容
		$('#outParameter').empty();// 清空外部参数内容
		var selectElement = "";
		if (selection[0].isSelected) {
			selectElement = selection[0];
		}
		var description = selectElement.description;// 控件描述内容获取
		$('#controlDescription').css('display','block');
		$('#shuxingContent').css('display','block');
		$('#controlDescription').css('display','block');
		$("#caseNamee").append(
				"<div id='elementName'>元素名称:<span class='backblock' id=" + id
						+ ">" + selectElement.text + "</span></div>");// 元素名称内容插入
		$("#conDescription").append(
				"<div id='controlDescription'>" + description + "</div>");// 描述内容插入到标签
		showAttribute(selectElement, caseElements);
	}
	rightParameter();// 根据用户权限判断让右侧的参数修改和不可修改
	changeConditionColor(selection,mycanvas);//被点击的元素突出显示
}

//点击条件轴时，条件轴颜色改变
function changeConditionColor(selection,mycanvas){
	if(selection.length<=0){
		return;
	}
	if(selection[0].type == '011'){
		for(var i=0;i<caseElements.length;i++){
			if(selection[0].id == caseElements[i].id){
				caseElements[i].selected = true;
				
			}else{
				caseElements[i].selected = false;
			}
		}
	}else{
		for(var i=0;i<caseElements.length;i++){
			caseElements[i].selected = false;
		}
	}
	
	draw(mycanvas, elementTypes, caseElements);
	
}
function changeElementColor(selection,mycanvas){
	if(selection.length<=0){
		return;
	}
	if(selection[0].type == '011'){
		for(var i=0;i<caseElements.length;i++){
			if(selection[0].id == caseElements[i].id){
				caseElements[i].selected = true;
				selectConditionIndex = i;
			}else{
				caseElements[i].selected = false;
			}
		}
	}else{
		for(var i=0;i<caseElements.length;i++){
			caseElements[i].selected = false;
		}
	}
	if(currentConditionIndex == selectConditionIndex){
		return;
	}
	draw(mycanvas, elementTypes, caseElements);
	currentConditionIndex = selectConditionIndex;
}
// 查询基本用例树信息并注册点击事件在画布上绘制图形信息
function showBaseCaseTree(canvas, elementTypes) {
	var setting = {
		view : {
			dblClickExpand : true,// 双击节点时，是否自动展开父节点的标识
			showLine : true,// 是否显示节点之间的连线
			fontCss : {
				'color' : 'black',
				'font-weight' : 'bold'
			},// 字体样式函数
			selectedMulti : false
		// 设置是否允许同时选中多个节点
		},
		check : {
			chkStyle : "checkbox",// 复选框类型
			enable : true
		// 每个节点上是否显示 CheckBox
		},
		data : {
			simpleData : {// 简单数据模式
				enable : true,
				idKey : "id",
				pIdKey : "pId",
				rootPId : ""
			}
		},
		callback : {
			onClick : function(event, treeId, treeNode) {
				var id = treeNode.id;// 点击获取树状图内的用例的Id
				if (!treeNode.isParent) {
					getElementsByCaseId(id, canvas, elementTypes);
				}
			}
		}
	};
	var treeNodes;
	$.ajax({
		async : false,// 是否异步
		cache : false,// 是否使用缓存
		type : 'POST',// 请求方式：post
		dataType : 'json',// 数据传输格式：json
		data: {
			flag: "1"
		},
		url : "../../../basecase/queryBaseCaseTree",// 请求路径
		error : function() {
			// 请求失败处理函数
			danger("请求基本用例树出错");
		},
		success : function(data) {
			if(data.flag==0){
				// 请求成功后处理函数
				treeNodes = data.content;// 所有表格内基本用例
				var t = $("#casetree");
				// 加载基本用例树信息
				t = $.fn.zTree.init(t, setting, treeNodes);
			}else{
				danger(data.errorInfo);
			}
			
		}
	});

}
// 元素在画布上移动事件,参数ev事件源，currentObj拖动的对象，elementTypes元素类型
function dragover(ev, elementTypes) {
	var x = ev.offsetX;
	var y = ev.offsetY;
	var p = {
		x : x,
		y : y
	};
	var type = currentObj.type;
	var leve = currentObj.leve;
	var dragable = false;
	var maxY = elementTypes[elementTypes.length - 1].y2 + 10;
	var maxX = 0;
	if(caseElements.length>0){
		maxX = caseElements[caseElements.length - 1].x + caseElements[caseElements.length - 1].width + 20;
	}
	if (leve == "1") {
		if (x >= selectx1 && x <= selectx2 && y >= 110 && y <= maxY) {
			
			for (var i = 0; i < elementTypes.length; i++) {
				// 判断拖拽的图形元素是否在其类型的区域内与条件轴限定区域内
				if (elementTypes[i].name == type && y > elementTypes[i].y1
						&& y < elementTypes[i].y2) {
					if (!isExistElement(p, caseElements)) {
						dragable = true;
					}
				}
			}
		}
	} else if (leve == "3") {// 判断图形元素的绘制区域
		if (y > maxY && x > maxX && maxX!=0) {// 得到限定是画直线还是画图形的Y值(最后一条直线的Y)
			dragable = true;
		}
		if(caseElements.length<=0){//当绘图区域没有元素时，可以拖拽元素进去
			dragable = true;
		}
	}
	if (dragable) {
		ev.dataTransfer.dropEffect = "move";
	} else {
		ev.dataTransfer.dropEffect = "none";
	}
	ev.stopPropagation(); // 阻止冒泡事件
	ev.preventDefault(); // 清除默认事件
}
// 获取用例元素类型
function getElementTypes(addBaseCaseId, mycanvas) {
	elementTypes = [];
	$.ajax({
		type : "GET",
		url : "../../../basecase/queryCaseElementType",
		data : "",
		dataType : "json",
		async : false,
		success : function(data) {
			if (data.flag == 0) {
				data = data.content;
				for (var i = 0; i < data.length; i++) {
					// 生成9个父级元素各自限定区域的四个坐标值
					elementTypes.push({
						name : data[i].NAME,
						text : data[i].TEXT,
						x1 : 100,
						x2 : 740,
						y1 : 40 * (i + 1) + 70,
						y2 : 40 * (i + 2) + 70
					});
				}
				getElementsByCaseId(addBaseCaseId, mycanvas, elementTypes);// 绘制点击的基本用例内的元素
				return elementTypes;
			} else {
				return elementTypes;
			}
		},
		error : function() {
			return elementTypes;
		}
	});
}
// 将当前用例元素(下标为index)后面的所有元素位置进行偏移x,
function updatePosition(index, x) {
	for (var i = index; i < caseElements.length; i++) {
		var leftBorder = 100;
		var nx = caseElements[i].x + x;
		if (index > 0) {// 防止往前移动时与之前元素重叠
			if (i == index) {
				leftBorder = caseElements[index - 1].x
						+ caseElements[index - 1].width + 10;
			} else {
				leftBorder = caseElements[i - 1].x
						+ caseElements[i - 1].width + 10;
			}
		}
		if (nx > leftBorder) {
			caseElements[i].x = nx;
			if (caseElements[i].children) {
				for (var j = 0; j < caseElements[i].children.length; j++) {
					caseElements[i].children[j].x += x;
				}
			}
		}
	}
}
// 提交基本用例信息，点击提交前，先执行保存逻辑，再执行提交逻辑
function submitBaseCase(addBaseCaseId) {
	baseCaseEditeBool = false;//屏蔽复制粘贴快捷键
	BootstrapDialog.show({
		title : '基本用例信息提交',
		message : "确定提交此基本用例信息么？提交后将无法继续修改！",
		buttons : [ {
			icon : 'glyphicon glyphicon-check',
			label : '确定',
			cssClass : 'btn-primary',
			autospin : true,
			action : function(dialogRef) {
				reDrawCheckPoint(caseElements, elementTypes, mycanvas);
				// 保存按钮，保存数据
				saves();
				$.ajax({
					type : "POST",
					url : "../../../basecase/saveCaseAndElement",
					data : {
						"caseId" : addBaseCaseId,
						"elements" : JSON.stringify(caseElements)
					},
					success : function(data) {
						var flag = data.flag;
						if (flag == 0) {//点击提交时的保存执行成功后，再执行提交操作
							submitFun(addBaseCaseId);
						} else {
							var content = "提交失败！";
							danger(content);
						}
					}
				});
				
				baseCaseEditeBool = true;//释放复制粘贴快捷键
			}
		}, {
			label : '取消',
			action : function(dialogRef) {
				baseCaseEditeBool = true;//释放复制粘贴快捷键
				dialogRef.close();
			}
		} ]
	});
}

//点击提交时的保存执行成功后，再执行提交操作
function submitFun(addBaseCaseId){
	/* ajax向后台发送提交基本用例信息 */
	$.ajax({
		type : "POST",
		url : "../../../basecase/submitBaseCase",
		data : {
			"caseId" : addBaseCaseId,
		},
		success : function(data) {
			var flag = data.flag;
			if (flag == 0) {
				initButton(1);
				BootstrapDialog.alert({
					title : '提示',
					message : "用例提交成功!",
					type : BootstrapDialog.TYPE_SUCCESS
				});
				setTimeout(function() {
					BootstrapDialog.closeAll();
				}, 2000);
			} else if (flag == -1) {
				var t = BootstrapDialog.alert({
					title : '提示',
					message : "服务器异常，用例提交失败!",
					type : BootstrapDialog.TYPE_DANGER
				});
				setTimeout(function() {
					t.close();
				}, 2000);
			}
		},
		error : function(err) {
			BootstrapDialog.alert({
				title : '提示',
				message : "服务器异常!",
				type : BootstrapDialog.TYPE_DANGER
			});
			setTimeout(function() {
				BootstrapDialog.closeAll();
			}, 2000);
		}
	});
}


// 审核基本用例信息
function auditBaseCase(addBaseCaseId) {
	baseCaseEditeBool = false;//屏蔽复制粘贴快捷键
	BootstrapDialog
			.show({
				title : '基本用例信息审核',
				message : $(
						"<form class='form-inline' style='height:300px'></form>")
						.load('baseCaseAudit.html'),
				onshown : function() {
					// 初始化各个值
					$("#auditResult")
							.append(
									"<option value='2'>审核通过</option><option value='3'>审核不通过</option>");
				},
				buttons : [
						{
							icon : 'glyphicon glyphicon-check',
							label : '确定',
							cssClass : 'btn-primary',
							autospin : true,
							action : function(dialogRef) {
								var auditResult = $("#auditResult").val();
								var auditOpinion = $("#caseAudit").val();
								var versionNow = $(
										"input[name='versionNow']:checked")
										.val();
								// 判断类型是否为空
								if (auditResult == "") {
									var t = BootstrapDialog.alert({
										title : '提示',
										message : "请选择审核结果！",
										type : BootstrapDialog.TYPE_DANGER
									});
									setTimeout(function() {
										t.close();
									}, 2000);
									return false;
								}
								// 判断审核意见是否为空
								if (auditOpinion == "") {
									var t = BootstrapDialog.alert({
										title : '提示',
										message : "审核意见不能为空!",
										type : BootstrapDialog.TYPE_DANGER
									});
									setTimeout(function() {
										t.close();
									}, 2000);
									return false;
								}
								/* ajax向后台发送新建用例的数据 */
								$.ajax({
									type : "POST",
									url : "../../../basecase/auditBaseCase",
									data : {
										"caseId" : addBaseCaseId,
										"result" : auditResult,
										"view" : auditOpinion,
										"versionNow" : versionNow
									},
									success : function(data) {
										var flag = data.flag;
										if (flag == 0) {
											initButton(auditResult);
											taskState = auditResult;
											success("用例审核成功!");
										} else{
											danger(data.errorInfo);
										}
									},
									error : function(err) {
										var content = "服务器异常!";
										danger(content);
									}
								});
								
								baseCaseEditeBool = false;//屏蔽复制粘贴快捷键
							}
						}, {
							label : '取消',
							action : function(dialogRef) {
								dialogRef.close();
								baseCaseEditeBool = false;//屏蔽复制粘贴快捷键
							}
						} ]
			});
}
// 展示用例基本信息
function showBaseCaseInfo(baseCaseData) {
	if(taskState == 0){
		
		baseCaseEditeBool = false;//屏蔽复制粘贴快捷键
		
		BootstrapDialog.show({
			title : '基本用例信息',
			message : $("<form class='form-inline' style='height:300px'></form>")
					.load('baseCaseAdd.html'),
			onshown : function() {
				baseMsgViewData(baseCaseData);
			},
			buttons : [ {
				icon : 'glyphicon glyphicon-check',
				label : '保存',
				cssClass : 'btn-primary',
				autospin : true,
				action : function(dialogRef) {
					var caseNum = $("#caseNum").val();
					var caseContent = $("#caseContent").val();
					// 判断描述是否为空
					if (caseContent == "") {
						var t = BootstrapDialog.alert({
							title: '提示',
							message: "基本用例描述不能为空!",
							type: BootstrapDialog.TYPE_DANGER
						});
						setTimeout(function() {
							t.close();
						}, 2000);
						return false;
					}
					// 判断描述过长
	                if(caseContent.length>=250){
	                	var t = BootstrapDialog.alert({ title: '提示',
				            message: "基本用例描述不能超过250个字符!",
				            type: BootstrapDialog.TYPE_DANGER});
						setTimeout(function (){
							t.close();
						},2000);
	                       return false;
	                }
					// 判断基本用例编号是否为空
					if (caseNum == "") {
						var t = BootstrapDialog.alert({
							title: '提示',
							message: "基本用例编号不能为空!",
							type: BootstrapDialog.TYPE_DANGER
						});
						setTimeout(function() {
							t.close();
						}, 2000);
						return false;
					}
					// 判断基本用例编号过长
					if (caseNum.length>=20) {
						var t = BootstrapDialog.alert({
							title: '提示',
							message: "基本用例编号不能超过20个字符!",
							type: BootstrapDialog.TYPE_DANGER
						});
						setTimeout(function() {
							t.close();
						}, 2000);
						return false;
					}
					$.ajax({
						type : "POST",
						url : "../../../basecase/editeBaseCase",
						dataType : "json",
						data : {
							"id" : baseCaseData[0].ID,
							"code" : $('#caseNum').val(),
							"content":$('#caseContent').val()
						},
						success : function(data) {
							var flag = data.flag;
							if (flag == 0) {
								var content = "保存成功!";
								success(content);
								getBaseCaseByCaseId(baseCaseData[0].ID);
							} else {
								danger(data.errorInfo);
							}
						}
					});
					dialogRef.close();
					
					baseCaseEditeBool = true;//释放复制粘贴快捷键
					
				}
			}, {
				label : '取消',
				action : function(dialogRef) {
					dialogRef.close();
					
					baseCaseEditeBool = true;//释放复制粘贴快捷键
				}
			} ]
		});
	}else{
		BootstrapDialog.show({
			title : '基本用例信息',
			message : $("<form class='form-inline' style='height:300px'></form>")
					.load('baseCaseAdd.html'),
			onshown : function() {
				baseMsgViewData(baseCaseData);
			}
		});
	}
}

function baseMsgViewData(baseCaseData){
	// 初始化各个值
	$("#caseType").append(
			"<option value='" + baseCaseData[0].TYPE + "'>"
					+ baseCaseData[0].TNAME + "</option>");
	$("#caseName").val(baseCaseData[0].NAME);
	$("#caseContent").val(baseCaseData[0].CONTENT);
	$("#caseNum").val(baseCaseData[0].CODE);
	$("#caseType")[0].disabled = true;
	$("#caseName")[0].disabled = true;
	if(taskState == 0){
		$("#caseContent")[0].disabled = false;
		$("#caseNum")[0].disabled = false;
	}else{
		$("#caseContent")[0].disabled = true;
		$("#caseNum")[0].disabled = true;
	}
}
// 展示左侧用例元素信息
function showLeftElement() {
	// 左侧基本用例元素信息加载
	$.ajax({
		type : "GET",
		url : "../../../basecase/queryCaseElement",
		data : "",
		dataType : "json",
		async : false,
		success : function(data) {
			if (data.flag == "0") {
				var elementData = data.content;// 请求得到基本用例信息
				var htmla = "";
				// 遍历获取到的用例元素放入相应位置并绑定拖动事件
				for (var i = 0; i < elementData.length; i++) {
					var lev = elementData[i].leve;
					var type = elementData[i].type;
					if (lev == "1") {
						var c = $("#home div[id='" + type + "']");
						if (c.length > 0) {
							$("#" + type).append(
									"<a draggable='true' id='"
											+ elementData[i].id + "' "
											+ "name='" + elementData[i].name
											+ "' type='" + elementData[i].type
											+ "' leve='1' elementId='"
											+ elementData[i].elementId + "' >"
											+ elementData[i].text + "</a>");
						} else {
							$("#home").append("<div id='" + type + "'></div>");
							$("#" + type).append(
									"<a draggable='true' id='"
											+ elementData[i].id + "' "
											+ "name='" + elementData[i].name
											+ "' type='" + elementData[i].type
											+ "' leve='1' elementId='"
											+ elementData[i].elementId + "' >"
											+ elementData[i].text + "</a>");
						}
					} else if (elementData[i].leve == "3") {
						// 图形控件的插入
						htmla += "<a draggable='true' id='" + elementData[i].id
								+ "' " + "name='" + elementData[i].name
								+ "' type='" + elementData[i].type
								+ "' leve='3' elementId='"
								+ elementData[i].elementId + "' >"
								+ elementData[i].text + "</a>";
						/* 图形控件4个li标签插入 */
						$("#Graphics")[0].innerHTML = htmla;
					}
				}
				for (var i = 0; i < elementData.length; i++) {
					$("#" + elementData[i].id)[0].ondragstart = function(ev) {
						ev = ev || window.event;
						// 设置数据，保存在dataTransfer中的数据只能在drop事件处理函数中处理
						ev.dataTransfer.setData("id", ev.currentTarget.id);
						ev.dataTransfer.setData("name", ev.currentTarget.name);
						ev.dataTransfer.setData("type", ev.currentTarget.type);
						ev.dataTransfer.setData("leve",
								ev.target.attributes["leve"].value);
						ev.dataTransfer.setData("elementid",
								ev.target.attributes["elementId"].value);
						currentObj = {};
						currentObj.type = ev.target.type;
						currentObj.leve = ev.target.attributes["leve"].value;
					};
				}
			} else {
				danger(data.errorInfo);
			}
		}
	});
}
// 基本用例保存
function baseCaseSave(addBaseCaseId, caseElements) {
	// 保存按钮，保存数据
	saves();
	console.log(caseElements);
	$.ajax({
		type : "POST",
		url : "../../../basecase/saveCaseAndElement",
		data : {
			"caseId" : addBaseCaseId,
			"elements" : JSON.stringify(caseElements)
		},
		success : function(data) {
			var flag = data.flag;
			if (flag == 0) {
				var content = "保存成功!";
				success(content);
			} else {
				var content = "保存失败！";
				danger(content);
			}
		}
	});
}
// 根据用例元素名称获取用例元素类型
function getElementType(name, elementTypes) {
	for (var i = 0; i < elementTypes.length; i++) { /* 10条数据遍历 */
		if (name == elementTypes[i].name) {
			return elementTypes[i];
		}
	}
	return null;
}
// 将子元素添加到元素指定父元素中,并返回元素
function pushParentElement(element, caseElements) {
	var x1 = element.x;
	var y1 = element.y;
	var leve = element.leve;
	var length = caseElements.length;
	var addElement = false;
	if (length == 0) {
		element.displayOrder = 1;
		caseElements.splice(0, 0, element);
	} else {
		for (var i = 0; i < length; i++) {
			var px1 = caseElements[i].x - 20;
			var px2 = caseElements[i].x + caseElements[i].width;
			if (leve == 1) {// 添加基本用例到条件轴
				if (x1 >= px1 && x1 <= px2) {
					element.parentId = caseElements[i].id;
					if (caseElements[i].children == null) {
						caseElements[i].children = [];
					}
					var childrenLenght = caseElements[i].children.length;
					var addChildern = false;
					var addChildernStart = false;
					var addChildernEnd = false;
					var xStart = 0;
					var yStart = 0;
					var xEnd = 0;
					var yEnd = 0;
					if (childrenLenght == 0) {// 第一次添加子元素
						element.displayOrder = 1;
						caseElements[i].children.splice(0, 0, element);
						addChildernStart = true;
						addChildern = true;
					} else {
						xStart = caseElements[i].children[0].x;
						yStart = caseElements[i].children[0].y;
						xEnd = caseElements[i].children[childrenLenght - 1].x;
						yEnd = caseElements[i].children[childrenLenght - 1].y;
						for (var j = 0; j < childrenLenght; j++) {
							var x2 = caseElements[i].children[j].x;
							var y2 = caseElements[i].children[j].y;
							var x3 = 0;
							var y3 = 0;
							if (j == childrenLenght - 1) {
								x3 = caseElements[i].children[j].x;
								y3 = caseElements[i].children[j].y;
							} else {
								x3 = caseElements[i].children[j + 1].x;
								y3 = caseElements[i].children[j + 1].y;
							}
							if ((x1 < xStart || (x1 == xStart && y1 < yStart))
									&& !addChildernStart) {// 添加到最开始位置且循环中仅添加一次
								element.displayOrder = 1;
								caseElements[i].children.splice(0, 0, element);
								addChildernStart = true;
								addChildern = true;
							} else if ((x1 > xEnd || (x1 == xEnd && y1 > yEnd))
									&& !addChildernEnd) {// 添加到最后位置
								element.displayOrder = 1 + childrenLenght;
								caseElements[i].children.splice(childrenLenght,
										0, element);
								addChildern = true;
								addChildernEnd = true;
								//x1:拖入的目标
								//x2:当前遍历的目标
								//x3:当前遍历的目标的下一个目标
								//拖入目标的位置只可能是4种情况，1：三个同列，2：当前目标和上一个同列，和下一个不同列，3：当前目标和下一个同列，和当前不同列，4:三个都不同列
							} else if (((x1==x2&&y1>y2&&x1<x3)||(x1>x2&&x1==x3&&y1<y3)||(x1>x2&&x1<x3)|| (x1 == x2&& x2 == x3 && y1 > y2 && y1 < y3))&& !addChildern&& !(x1 == x2 && y1 == y2)&& !(x1 == x3 && y1 == y3)) {// 当前元素在某一列开头、末尾或中间插入，不可元素重叠
								element.displayOrder = caseElements[i].children[j].displayOrder + 1;
								addChildern = true;
								caseElements[i].children.splice(j + 1, 0,
										element);
							}
							if (addChildernEnd) {// 不是在最后位置添加元素时需要更新之前元素顺序
								break;
							} else {
								if (addChildern) {// 添加元素后数组长度增加一
									caseElements[i].children[j + 1].displayOrder = j + 2;
								} else {
									caseElements[i].children[j].displayOrder = j + 1;
								}
							}
						}
					}

				}
			} else {// 添加条件轴等元素到用例元素中
				var px3 = 0;
				var px4 = 0;
				if (i == length - 1) {
					px3 = caseElements[i].x - 10;
					px4 = caseElements[i].x + caseElements[i].width - 10;
				} else {
					px3 = caseElements[i + 1].x - 10;
				}
				
				if ((x1 > px4 && px4 != 0) || (px3 > x1 && x1 > px2)) {// 往后追加元素或两元素之间插入元素
					
					element.displayOrder = i + 2;
					caseElements.splice(i + 1, 0, element);
					addElement = true;
				}else if(i==0&&x1<px3){//最前面插入条件轴
					element.displayOrder = i + 1;
					caseElements.splice(i, 0, element);
					for(var n = 1;n<caseElements.length;n++){
						caseElements[n].displayOrder = caseElements[n].displayOrder+1;
					}
				} else {
					if (addElement) {// 添加元素后数组长度增加一
						caseElements[i + 1].displayOrder = i + 2;
					} else {
						caseElements[i].displayOrder = i + 1;
					}
				}
			}
		}
	}
	return caseElements;
}
// 根据元素ID和当前位置信息,生成元素信息，然后在画布上绘画此元素，并将此元素信息添加到全局变量中，并返回此对象
function getCaseElementInstance(mycanvas, elementId, x, y, caseElements,
		elementTypes) {
	var callback=arguments[6];
	$.ajax({
		type : "POST",
		url : "../../../basecase/getCaseElement",
		data : {
			elementId : elementId,
			x : x,
			y : y
		},
		dataType : "json",
		async : false,
		success : function(data) {
			var obj = data.content;// 新生成的图形元素的数据
			if (obj != null && obj != undefined) {
				var p = {
					x : 0,
					y : 0
				};
				if (obj.leve == 1) { // 通过leve（大类）进行判断是否画矩形
					p = {
						x : x + 5,
						y : y + 5
					};
					// drawDiagonal(mycanvas,obj);// 绘制小矩形
					var diagonal = tDrawCanvas.getDrawing('diagonal', {
						obj : obj
					});
					diagonal.draw();
					if(obj.name == "010001"){//延时默认5秒
						obj.data[0].value='5';
					}
					
					//设置按键输入，jtc信号，平调信号的默认显示和默认值
					var index = 0;
					if(obj.name == "004002" || obj.name == "007001"){
						index = 1;
					}else if(obj.name == "004004"){
						index = 0;
					}
					if(obj.name == "004002" || obj.name == "007001" ||obj.name == "004004"){
						var valueId = obj.data[index].dic[0].id;
						if(obj.data[index].value){
							valueId = obj.data[index].value;
						}	
						for(var n =0;n<obj.data[index].dic.length;n++){
							if(obj.data[index].dic[n].id == valueId){
								obj.text = obj.data[index].dic[n].name;
								obj.data[index].value = obj.data[index].dic[n].id;
								break;
							}
						}
					}
					
					// 根据obj位置信息判断当前节点的父节点并将其加入其中
					caseElements = pushParentElement(obj, caseElements);
				} else if (obj.leve == 3) {
					var type = obj.type;
					obj.children = [];// 存放条件轴内元素的数组
					obj.parentId = 0;// 后台区分数据用的参数
					if (type == "011") {
						// 画条件轴
						p = {
							x : x - 20,
							y : y - 5
						};
						obj.width = 90;// 矩形的默认宽度
						obj.color = 'rgb(220,20,60)';// 三角形的初始颜色
						// drawConditionArea(mycanvas,obj,elementTypes);// 绘制条件轴
						var conditionArea = tDrawCanvas.getDrawing(
								'conditionArea', {
									obj : obj,
									elementTypes : elementTypes
								});
						conditionArea.draw();
						caseElements = pushParentElement(obj, caseElements);
					} else if (type == "012") {
						p = {
							x : x,
							y : y - 65
						};
						// drawSignal(mycanvas,obj);
						var signal = tDrawCanvas.getDrawing('signal', {
							obj : obj
						});
						signal.draw();
						caseElements = pushParentElement(obj, caseElements);
					} else if (type == "013") {
						// drawGraph(mycanvas);
						var graph = tDrawCanvas.getDrawing('graph');
						graph.draw();
					} else if (type == "014") {
						p = {
							x : x,
							y : y - 65
						};
						// drawKvalueMap(mycanvas,obj);
						var kvalueMap = tDrawCanvas.getDrawing('kvalueMap', {
							obj : obj
						});
						kvalueMap.draw();
						caseElements = pushParentElement(obj, caseElements);
					}
				}
				canvasClick(p, caseElements, elementTypes, mycanvas);
			}
			callback&&callback();
			return caseElements;
		}
	});
}
// 展示条件轴内的条件组合
function showConditions(combination) {
	var showcombination = combination.childrenAttr;// 拿到需要展示的条件组合
	for (var i = 0; i < showcombination.length; i++) {// 遍历条件组合数据
		var divs = $("<div class='curs'></div>");// 存放需要展示的条件组合
		// 展示第一个框 and or
		if (showcombination[i].parentRelation == "null"
				|| showcombination[i].parentRelation == null
				|| showcombination[i].parentRelation == "") {
		} else {
			divs
					.append($("<select class='andor' disabled='true'><option>"
							+ showcombination[i].parentRelation
							+ "</option></select>"));
		}

		// 展示第二个框，系别
		if (showcombination[i].departmentId == "null"
				|| showcombination[i].departmentId == null
				|| showcombination[i].departmentId == "") {
		} else {
			if (showcombination[i].departmentId == "1") {
				divs
						.append($("<select class='department' disabled='true'><option id='1'>I系A模</option></select>"));
			} else if (showcombination[i].departmentId == "3") {
				divs
						.append($("<select class='department' disabled='true'><option id='2'>I系A/B模</option></select>"));
			}  else if (showcombination[i].departmentId == "4") {
				divs
						.append($("<select class='department' disabled='true'><option id='2'>II系A模</option></select>"));
			} else if (showcombination[i].departmentId == "8") {
				divs
						.append($("<select class='department' disabled='true'><option id='2'>II系B模</option></select>"));
			} else if (showcombination[i].departmentId == "12") {
				divs
						.append($("<select class='department' disabled='true'><option id='2'>II系A/B模</option></select>"));
			}else {
				divs
						.append($("<select class='department' disabled='true'><option id='0'>四模</option></select>"));
			}

		}

		// 展示第二个框,灯,速度，压力
		if (showcombination[i].conditionId) {
			divs.append($("<select class='condition' disabled='true'><option id='"
					+ showcombination[i].conditionId + "' data='"
					+ showcombination[i].script + "'>"
					+ showcombination[i].conditionName + "</option></select>"));
		}
		// 第三个框 <= >= =
		if (showcombination[i].relation) {
			divs.append($("<select class='symbol' disabled='true'><option>"
					+ showcombination[i].relation + "</option></select>"));
		}
		// 第四个框,用户设置的值
		var value = showcombination[i].displayName;
		if (value == "" || value == null) {
			value = showcombination[i].value;
			for(var k = 0;k<conditions.length;k++){
				if(conditions[k].id == showcombination[i].conditionId){
					if(conditions[k].dicList){//此时最后一个框为文字
						for(var m = 0;m<conditions[k].dicList.length;m++){
							if(conditions[k].dicList[m].id == showcombination[i].value){
								value = conditions[k].dicList[m].name;
							}
						}
					}
				}
			}
		}
		divs.append($("<input class='enters' id=" + showcombination[i].value
				+ " value=" + value + " readOnly></input>"));
		// 添加一个删除按钮
		divs.append("<button class='delete'>删除</button>");
		var addCondition = $("<div class='addCondition'></div>");
		addCondition.append(divs);
		$("#elementContents").append(addCondition);
		
		updateRelationData();
	}
	// 给删除按钮注册事件
	$(".addCondition").on('click', 'button', function deletes() {// 删除新建的条件组合
		if(!baseCaseEditeBool){
			return;
		}
		$(this).parent().parent().remove();
		updateRelationData();
	});
}
// 显示右侧属性信息
function showAttribute(selectElement, caseElements) {
	var shuXing = selectElement.data;// 拿到所有的data数据
	$('#externalParameter').css('display','none');//默认外部参数的div为隐藏状态
	$('#controlDescription').css('display','block');
	$('#shuxingContent').css('display','block');
	if (shuXing.length > 0) {
		var trainType = "";// 列车类型
		var trainBZ = "";// 标识
		for (var j = 0; j < shuXing.length; j++) {
			// 通过data的type属性判断input的类型
			// input是文本输入框且data数据中的ranger不是null时，获取限定值
			var shuxing = shuXing[j];
			var value1 = shuxing.value;
			var name = shuxing.name;
			var displayValue = shuxing.displayValue;
			if (value1 == null) {
				value1 = shuxing.defultValue;
			}
			if (shuxing.type == "1") {
				// 拿到输入数字的限定值
				var range = shuxing.range;
				var rangValue = "";
				var div = "";
				if (range != null) {
					var nums = range.split(',');
					var minnum = parseInt(nums[0]);
					var maxnum = parseInt(nums[1]);
					rangValue = "min='" + minnum + "' max='" + maxnum + "'";
				}
				if(shuxing.unit){
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.text + "</span>"
							+ "<input type='number' id='" + shuxing.id + "' name='"
							+ name + "' value='" + value1 + "'" + rangValue
							+ " onInput='set_a_value(this)'><span style='width:40px;margin-left:5px'>" +shuxing.unit+ "</span></div>");
				}else{
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.text + "</span>"
							+ "<input type='number' id='" + shuxing.id + "' name='"
							+ name + "' value='" + value1 + "'" + rangValue
							+ " onInput='set_a_value(this)'>" +"</div>");
				}
				if (shuxing.required == "0") {
					$('#shuxingContent').css('display','block');
					$("#elementContents").append(div);
				} else {
					$('#externalParameter').css('display','block');//当有外部参数时，外部参数div才显示
					$("#outParameter").append(div);
				}

			} else if (shuxing.type == "2") {// 下拉框
				var dic = shuxing.dic;
				var div = "";
				if (shuxing.atrributeId == "78") {// 如果属性的ID是78
					$(".conditionsTemplate").remove();// 删除条件组合
					$(".headInformation").remove();// 删除头部信息
					generateConditions(shuxing);// 生成条件组合功能的函数
				} else {
					if (name == "007004003") {
						trainType = value1;
					} else if (name == "007004004") {
						trainBZ = value1;
					}
					if (shuxing.name == "007004010") {// 起始站名 输入下拉
						div = "<div class='defaultProperty'>"
								+ "<span>"
								+ shuxing.text
								+ "</span>"
								+ "<input type='text' style='width:25px' name='"+name+"'  onchange='startStationPYChange(this)' onkeyup='validate(this,1)'>"
								+ "<select id='"
								+ shuxing.id
								+ "' value= '"
								+ value1
								+ "' name='"
								+ name
								+ "' onchange='startStationChange(this)'></select></div>";
					} else if (shuxing.name == "007004013") {// 发车方向下拉选项
						div = ("<div class='defaultProperty'>" + "<span>"
								+ shuxing.text + "</span>" + "<select id='"
								+ shuxing.id + "' value= '" + value1
								+ "' name='" + name
								+ "' onchange='directionChange(this)'>"
								+ "</select>" + "</div>");
					} else if (shuxing.name == "007004014") {// 终止站
//						if(value1 == "null"){
//							value1 = "";
//						}
						div = "<div class='defaultProperty'>"
								+ "<span>"
								+ shuxing.text
								+ "</span>"
								+ "<input type='text' style='width:25px' onchange='stopStationPYChange(this)' onkeyup='validate(this,1)'>"
								+ "<select id='" + shuxing.id + "' value= '"
								+ value1 + "' name='" + name
								+ "' ></select></div>";
					} else {
						div = ("<div class='defaultProperty'>" + "<span>"
								+ shuxing.text + "</span>" + "<select id='"
								+ shuxing.id + "' value= '" + value1
								+ "' name='" + name
								+ "' onchange='set_a_value(this)'>"
								+ "</select>" + "</div>");
					}

					if (shuxing.required == "0") {
						$('#shuxingContent').css('display','block');
						$("#elementContents").append(div);
					} else {
						$('#externalParameter').css('display','block');//当有外部参数时，外部参数div才显示
						$("#outParameter").append(div);
					}
					/**
					 * 如果是下拉框,则将其值设置为value
					 */
//					if($('#' + shuxing.id).is('select')){
//						$("#" + shuxing.id).append(
//								"<option id=" + value1
//										+ " selected='selected' >"
//										+ displayValue + "</option>");
//					}
					if(displayValue != null && value1 != "null"){
						if (name == "007004010" || name == "007004011"
							|| name == "007004013" || name == "007004014"
							|| name == "007004015") {
							$("#" + shuxing.id).append(
									"<option id=" + value1
											+ " selected='selected' >"
											+ displayValue + "</option>");
						}
					}
					if (shuxing.dic != null) {
						for (var i = 0; i < dic.length; i++) {
							var dicId = dic[i].id;
							var dicName = dic[i].name;
							if (value1 == dicId) {
								$("#" + shuxing.id).append(
										"<option id='" + dicId + "'value='"
												+ dicName
												+ "' selected='selected' >"
												+ dicName + "</option>");
							} else {
								$("#" + shuxing.id).append(
										"<option id='" + dicId + "' value= '"
												+ dicName + "'>" + dicName
												+ "</option>");
							}
						}
					} else {//

					}
					
				}
				if (shuxing.childrenAttr !== null) {// 条件轴内有条件组合
					showConditions(shuxing);// 展示条件轴内的条件组合
				}
			}else if(shuxing.type == "3"){
				div = ("<div class='defaultProperty'>" + "<span style='display:inline;vertical-align:middle'>"
						+ shuxing.text + "</span>"
						+ "<a class='input-group date' id='datetimepicker1' style='display:inline-block;vertical-align:middle'>" +
								"<input type='text'  class='form-control'  id='" + shuxing.id + "' onChange='set_Time_value(this)' style='width: 160px; height: 30px;background-color:#161b2f;border:1px solid #53597B;color:#ffffff' />" +
								"<span class='input-group-addon' style='float: left; width: 50px; height: 30px;background-color:#337ab7;border:1px solid #53597B'>" +
										"<span id='datetimepicker2'  class='glyphicon glyphicon-calendar' style='width:25px;margin-left:0px;color:#e0ecff'></span></span></a>"+ "</div>");
				if (shuxing.required == "0") {
					$('#shuxingContent').css('display','block');
					$("#elementContents").append(div);
				} else {
					$('#externalParameter').css('display','block');//当有外部参数时，外部参数div才显示
					$("#outParameter").append(div);
				}
				Datetime(shuxing,shuxing.id);
			}else if(shuxing.type == "4"){//文本输入框
				if(value1 == "null"){
					value1 = "-1";
				}
				var div = "";
				if(shuxing.unit){
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.text + "</span>"
							+ "<input id='" + shuxing.id + "' name='"
							+ name + "' value='" + value1 + "'"
							+ " onInput='set_a_value(this)'><span style='width:40px;margin-left:5px'>" +shuxing.unit+ "</span></div>");
				}else{
					div = ("<div class='defaultProperty'>" + "<span>"
							+ shuxing.text + "</span>"
							+ "<input id='" + shuxing.id + "' name='"
							+ name + "' value='" + value1 + "'"
							+ " onInput='set_a_value(this)'>" +"</div>");
				}
				
				if (shuxing.required == "0") {
					$('#shuxingContent').css('display','block');
					$("#elementContents").append(div);
				} else {
					$('#externalParameter').css('display','block');//当有外部参数时，外部参数div才显示
					$("#outParameter").append(div);
				}
				
				if(value1 !=""){
//					var signal = tDrawCanvas.getDrawing('signal', {
//						obj : obj
//					});
//					signal.draw();
				}

			}else if(shuxing.type == "5"){//始发站
				if(value1 == "null"){
					value1 = "";
				}
				var dic = shuxing.dic;
				var div = "";
				div = "<div class='defaultProperty'>"
						+ "<span>"
						+ shuxing.text
						+ "</span>"
						+ "<input type='text' style='width:25px;' name='"+name+"' onchange='startStationPYChange(this)' onkeyup='validate(this,1)'>"
						+ "<select id='"
						+ shuxing.id
						+ "' value= '"
						+ value1
						+ "' name='"
						+ name
						+ "'></select></div>";

				if (shuxing.required == "0") {
					$('#shuxingContent').css('display','block');
					$("#elementContents").append(div);
				} else {
					$('#externalParameter').css('display','block');//当有外部参数时，外部参数div才显示
					$("#outParameter").append(div);
				}
				/**
				 * 如果是下拉框,则将其值设置为value
				 */
				if(displayValue && displayValue!=null){
					$("#" + shuxing.id).append(
							"<option id=" + value1
									+ " selected='selected' >"
									+ displayValue + "</option>");
				}
				if (shuxing.dic != null) {
					for (var i = 0; i < dic.length; i++) {
						var dicId = dic[i].id;
						var dicName = dic[i].name;
						if (value1 == dicId) {
							$("#" + shuxing.id).append(
									"<option id='" + dicId + "'value='"
											+ dicId
											+ "' selected='selected' >"
											+ dicName + "</option>");
						} else {
							$("#" + shuxing.id).append(
									"<option id='" + dicId + "' value= '"
											+ dicName + "'>" + dicName
											+ "</option>");
						}
					}
				}
			}
		}
		if (selectElement.name == "007004") {
			// 初始化列车类型下拉框值和车种标识下拉值
			getLKJTrainType("0101120180502134514001852", trainType,
					trainBZ);
		}
	}
}

function set_Time_value(th) {// th this用来获取属性值，ys就是整个元素对象
	if(!checkDateTime($(th).val())){//输入的时间格式校验
		$(th).val('-1');
		return;
	}
	var ys = "";
	saves();
	var id = $(th).parent().parent().parent().prev().children().children(".backblock")
			.attr("id");
	for (var i = 0; i < caseElements.length; i++) {
		var children = caseElements[i].children;
		for (var k = 0; k < children.length; k++) {
			if (id == children[k].id) {
				ys = children[k];
			}
		}
	}

	var data = ys.data;
	for (var i = 0; i < data.length; i++) {
		// 重新绘制元素矩形。精确到元素小矩形范围的清除和重绘
		// 计算清除的范围
		var x = ys.x;
		var y = ys.y;
		var width = ys.width;
		var height = ys.hight;
		context.clearRect(x, y, width, height);// 清空需要更新数值的小矩形
		// redrawDiagonal(context,ys);//重绘元素小矩形的函数
		var rediagonal = tDrawCanvas.getDrawing('rediagonal', {
			obj : ys
		});
		rediagonal.draw();
		break;
	}
}

//设置日期时间控件
function Datetime(shuxing,id) {
    $('#datetimepicker2').datetimepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy-mm-dd hh:ii:ss',//显示格式
        minView: 0,//设置只显示到月份
        initialDate: new Date(),
        autoclose: true,//选中自动关闭
        todayBtn: true,//显示今日按钮
        locale: moment.locale('zh-cn'),
    }).on('changeDate', function(ev){
    	$('#'+id).val(formatDateTime(Number(ev.date.valueOf())));
    });
    
    //默认获取当前日期
    if(shuxing.value){
    	if(shuxing.value!=-1){
    		document.getElementById(id).value = setTimeToTimeFormat(shuxing.value);
    	}else{
    		document.getElementById(id).value = shuxing.value;
    	}
    }else{
    	document.getElementById(id).value = "-1";
    }
    
}

//根据时间数字转换为时间格式20180723140101  2018-07-24 13:35:08
function setTimeToTimeFormat(timeStr){
	var timeFormat = "";
	var numArray = timeStr.split("");
	timeFormat = numArray[0]+numArray[1]+numArray[2]+numArray[3]+"-"+
	numArray[4]+numArray[5]+"-"+numArray[6]+numArray[7]+" "+
	numArray[8]+numArray[9]+":"+numArray[10]+numArray[11]+":"+numArray[12]+numArray[13];
	return timeFormat;
}

// 生成条件组合功能的函数
function generateConditions(combination) {
	var departmentId = "1";// 选中的系别value
	var conditionId = "";// 选中name的option的ID
	var conditionVal = "";// 选中name的option的内容
	var symbolVal = "";// 选中的符号内容
	caseElementValId = combination.id;// 获取caseElementValid
	conditions = combination.conditions;// 拿到第一个下拉框的内容
	// 生成条件组合模板
	var createobj = jQuery("<div class='conditionsTemplate'>"
			+ "<select class='andor'>" + "<option></option>"
			+ "<option>and</option>" + "<option>or</option>" + "</select>"
			+ "<select class='department'>"
			+ "<option id='1'>I系A模</option>"
			+ "<option id='3'>I系A/B模</option>"
			+ "<option id='4'>II系A模</option>"
			+ "<option id='8'>II系B模</option>"
			+ "<option id='12'>II系A/B模</option>"
			+ "<option id='15'>四模</option>"
			+ "</select>" + "<select class='condition'>" + "</select>"
			+ "<select class='symbol'>"
			+ "<option>=</option>" + "<option>></option>"
			+ "<option>>=</option>" + "<option><</option>"
			+ "<option><=</option>"+ "<option>!=</option>" + "</select>"
			+ "<input class='showLabels' type = 'number'></input>"
			+ "<button class='showButton'>添加</button>" + "</div>");

	var div = $("<div class='conditionTemplate'></div>");// 创建存放条件模板的div
	$('#shuxingContent').css('display','block');
	$("#elementContents").append(div);// 插入到属性区域
	$(".conditionTemplate").append(
			"<h4 class='headInformation'>" + combination.text + "</h4>");
	$(".conditionTemplate").append(createobj);// 插入条件组合模板
	$(".conditionsTemplate .condition").append("<option></option>");

	$(".department").change(function() {
		departmentId = $(".department option:selected").attr("id");// 拿到被选中的option的id
	});

	for (var i = 0; i < conditions.length; i++) {
		var op = $("<option id=" + conditions[i].id + " data="
				+ conditions[i].script + ">" + conditions[i].name + "</option>");
		$(".conditionsTemplate .condition").append(op);
	}

	$(".condition")
			.change(
					function() {// 拿到被选中的option的ID
						conditionId = $(".condition option:selected")
								.attr("id");// 拿到被选中的option的ID
						conditionVal = $(".condition option:selected").val();// 拿到被选中的option的ID
						conditionData = $(".condition option:selected").attr(
								"data");// 拿到被选中的option的ID
						for (var i = 0; i < conditions.length; i++) {
							if (conditions[i].id == conditionId) {
								symbolVal ="=";
								if (conditions[i].dic != null) {// 条件组合第四个是下拉框
									// 如果里面有input和button标签时
									if ($(".conditionsTemplate").find(".enter").length !== 0
											&& $(".conditionsTemplate").find(
													".add").length !== 0) {
										$(".conditionsTemplate input").remove();
										$(".conditionsTemplate button")
												.remove();
										var dicList = conditions[i].dicList;// 拿到下拉框内的值
										$(".conditionsTemplate")
												.append(
														"<select class='dropDown'></select>");
										for (var k = 0; k < dicList.length; k++) {
											$(".dropDown").append(
													"<option id="
															+ dicList[k].id
															+ ">"
															+ dicList[k].name
															+ "</option>");
										}
										$(".conditionsTemplate")
												.append(
														"<button class='add'>添加</button>");
									} else {
										$(".conditionsTemplate .dropDown")
												.remove();
										$(".conditionsTemplate input").remove();
										$(".conditionsTemplate button")
												.remove();
										$(".conditionsTemplate")
												.append(
														"<select class='dropDown'></select>");
										var dicList = conditions[i].dicList;// 拿到下拉框内的值
										for (var k = 0; k < dicList.length; k++) {
											$(".dropDown").append(
													"<option id="
															+ dicList[k].id
															+ ">"
															+ dicList[k].name
															+ "</option>");
										}
										$(".conditionsTemplate")
												.append(
														"<button class='add'>添加</button>");
									}
									
									$(".add")[0].onclick = function() {
										if(!baseCaseEditeBool){
											return;
										}
										adds(departmentId, andorVal,
												conditionId, conditionData,
												conditionVal, symbolVal);
									};
									
									//如果是下拉框，那么关系默认为“=”
									$('.conditionsTemplate').find('.symbol').empty();
									$('.conditionsTemplate').find('.symbol').append("<option>=</option>");
									$('.conditionsTemplate').find('.symbol').append("<option>!=</option>");
									
								} else {// 条件组合第四个是输入框,功能正常
									if ($(".conditionsTemplate").find(".enter").length == 0
											&& $(".conditionsTemplate").find(
													".add").length == 0
											|| $(".conditionsTemplate").find(
													".dropDown").length !== 0) {// 如果div内没有Inpuit标签
										$(".conditionsTemplate .dropDown")
												.remove();
										$(".conditionsTemplate input").remove();
										$(".conditionsTemplate button")
												.remove();
										$(".conditionsTemplate")
												.append(
														"<input class='enter' type='number'></input>");
										$(".conditionsTemplate")
												.append(
														"<button class='add'>添加</button>");
										$(".add")[0].onclick = function() {
											if(!baseCaseEditeBool){
												return;
											}
											adds(departmentId, andorVal,
													conditionId, conditionData,
													conditionVal, symbolVal);
										};
									} else {
										return false;
									}
									//如果是输入框，那么关系恢复默认多个符号
									$('.conditionsTemplate').find('.symbol').empty();
									$('.conditionsTemplate').find('.symbol').append("<option>=</option><option>></option><option>>=</option><option><</option><option><=</option><option>!=</option>");
								}
							}
						}
					});
	$(".symbol").change(function() { // 获取选中的符号
		symbolVal = $(".symbol option:selected").val();
	});
	$(".andor").change(function() { // 获取选中关系
		andorVal = $(".andor option:selected").val();
	});
	
	updateRelationData();
}
// 点击添加按钮，将新组成的条件生成
function adds(departmentId, andorVal, conditionId, conditionData, conditionVal,
		symbolVal) {
	saves();
	var h4 = $("<div class='addCondition'></div>"); // 存放修改后的条件组合
	var department = "";
	var andor = "";
	var enterId = "";
	var enterName = "";

	if (andorVal != "") {
		andor = "<select class='andor' disabled='true'>" + "<option>" + andorVal + "</option>" + // 选中的是and还是or或者是空
																					// //选中的是and还是or或者是空
		"</select>";
	}

	if (departmentId != "") {
		if (departmentId == "1") {
			department = "<select class='department' disabled='true'>" + "<option id="
					+ departmentId + ">I系A模</option>" + "</select>";
		} else if (departmentId == "3") {
			department = "<select class='department' disabled='true'>" + "<option id="
					+ departmentId + ">I系A/B模</option>" + "</select>";
		} else if (departmentId == "4") {
			department = "<select class='department' disabled='true'>" + "<option id="
					+ departmentId + ">II系A模</option>" + "</select>";
		}else if (departmentId == "8") {
			department = "<select class='department' disabled='true'>" + "<option id="
					+ departmentId + ">II系B模</option>" + "</select>";
		}else if (departmentId == "12") {
			department = "<select class='department' disabled='true'>" + "<option id="
					+ departmentId + ">II系A/B模</option>" + "</select>";
		}else {
			department = "<select class='department' disabled='true'>" + "<option id="
					+ departmentId + ">四模</option>" + "</select>";
		}
	}
	if ($(".conditionsTemplate").find(".enter").length !== 0) {// 如果是输入框
		enterName = $(".conditionsTemplate .enter").val();// 取到输入框的值
		if(enterName == ""){
			danger("输入值不能为空！");
			return;
		}
	}
	if ($(".conditionsTemplate").find(".dropDown").length !== 0) {// 如果是下拉框
		enterName = $(".dropDown option:selected").val();
		enterId = $(".dropDown option:selected").attr("id");
	}
	if (enterId != "") {
		enterId = "id='" + enterId + "'";
	}
	var currentObjs = jQuery(// 重新拼接成用户修改后的值
	"<div class='curs'>" + andor + department + "<select class='condition' disabled='true'>"
			+ "<option id=" + conditionId + " data=" + conditionData + ">"
			+ conditionVal + "</option>" + // 选中的name值
			"</select>" + "<select class='symbol' disabled='true'>" + "<option >" + symbolVal
			+ "</option>" + // 选中的符号
			"</select>" + "<input disabled='true' class='enters' " + enterId + "value="
			+ enterName + " readonly></input>"
			+ "<button class='delete'>删除</button>" + "</div>");

	$("#elementContents").append(h4);// 存放新增的条件组合的div
	h4.append(currentObjs);// 添加的条件组合添加条件组合集合中
	$(".addCondition").on('click', 'button', function deletes() {// 删除新建的条件组合
		if(!baseCaseEditeBool){
			return;
		}
		$(this).parent().parent().remove();
		saves();
		//当条件数》=1时，则关系比不能为空
		updateRelationData();
	});
	
	//当条件数》=1时，则关系比不能为空
	updateRelationData();
}
// 点击右侧保存按钮方法修改全局变量caseElements
function saves() {
	// 拿到右侧所有属性所在的div
	var currentElements = getSelectElements(caseElements);// 获取选中元素下标
	var currentAttributes = [];
	var index = -1;
	var index1 = -1;
	var index2 = -1;
	if (currentElements.length == 1) {
		index = currentElements[0];
		currentAttributes = caseElements[index].data;
	} else if (currentElements.length == 2) {
		index1 = currentElements[0];
		index2 = currentElements[1];
		currentAttributes = caseElements[index1].children[index2].data;
	}
	for (var i = 0; i < currentAttributes.length; i++) {
		var newValue = "";
		var displayValue = "";
		var dic = "";// 动态dic
		if (currentAttributes[i].type == "1" || currentAttributes[i].type == "4" ) {
			if($('#' + currentAttributes[i].id).val() == ""|| $('#' + currentAttributes[i].id).val() == "null"){
				newValue = "";
			}else{
				newValue = $('#' + currentAttributes[i].id).val();
			}
		} else if (currentAttributes[i].type == "2" || currentAttributes[i].type == "5") {
			if (currentAttributes[i].atrributeId == "78") {// 条件组合
				currentAttributes[i].childrenAttr = packagingCondition();// 封装到这个集合中
			} else {
				if ($('#' + currentAttributes[i].id).length > 0
						&& $('#' + currentAttributes[i].id)[0].selectedOptions.length > 0) {
					var aaa = $('#' + currentAttributes[i].id)[0].selectedOptions[0].id;
					newValue = aaa == "" ? $('#' + currentAttributes[i].id)[0].value
							: aaa;
				} else {
					newValue = "";
				}
			}
			// }else if(currentAttributes[i].type=="3"){//复选框
			// var dic = currentAttributes[i].dic;
			// for(var j=0;j<dic.length;j++){
			// if($('#'+currentAttributes[i].id+dic[j].id)[0].checked){
			// newValue +=dic[j].id+",";
			// };
			// }
			//	        
			// }else if(currentAttributes[i].type=="4"){//单选按钮
			// var dic = currentAttributes[i].dic;
			// for(var j=0;j<dic.length;j++){
			// if($('#'+currentAttributes[i].id+dic[j].id)[0].checked){
			// newValue =dic[j].id;
			// };
			// }
			// }
		}else if (currentAttributes[i].type == "3") {
			var str = $('#' + currentAttributes[i].id).val();
			if(str!=-1){
				while(str.indexOf(" ")>=0){
					str = str.replace(' ',"");
				}
				while(str.indexOf("-")>=0){
					str = str.replace('-',"");
				}
				while(str.indexOf(":")>=0){
					str = str.replace(':',"");
				}
			}
			newValue = str;
		}
		if (currentElements.length == 1) {
			caseElements[index].data[i].value = newValue;
			if (caseElements[index].data[i].name=="011001006") {
				if(!$('#' + currentAttributes[i].id)[0] || $('#' + currentAttributes[i].id)[0].selectedOptions.length==0){//当没有数据时，为空
					dic = [ {
						id : newValue,
						name : ""
					} ];
					displayValue = "";
				}else{
					dic = [ {
						id : newValue,
						name : $('#' + currentAttributes[i].id)[0].selectedOptions[0].text
					} ];
					displayValue = $('#' + currentAttributes[i].id)[0].selectedOptions[0].text;
				}
				
				
				caseElements[index].data[i].dic = dic;
				caseElements[index].data[i].displayValue = displayValue;
			}
		} else if (currentElements.length == 2) {
			caseElements[index1].children[index2].data[i].value = newValue;
			var attrName = currentAttributes[i].name;
			
			if (attrName == "007004003" || attrName == "007004004"
					|| attrName == "007004010" || attrName == "007004011"
					|| attrName == "007004013" || attrName == "007004014"
					|| attrName == "007004015" || attrName == "001003001" || attrName=="011001006") {
				if($('#' + currentAttributes[i].id)[0].selectedOptions.length==0){//当没有数据时，为空
					dic = [ {
						id : newValue,
						name : ""
					} ];
					displayValue = "";
				}else{
					dic = [ {
						id : newValue,
						name : $('#' + currentAttributes[i].id)[0].selectedOptions[0].text
					} ];
					displayValue = $('#' + currentAttributes[i].id)[0].selectedOptions[0].text;
				}
				
				
				caseElements[index1].children[index2].data[i].dic = dic;
				caseElements[index1].children[index2].data[i].displayValue = displayValue;
			}else if($('#' + currentAttributes[i].id).is('select')){
				//如果是其他下拉菜单,则将displayValue存储
				if($('#' + currentAttributes[i].id)[0].selectedOptions.length==0){
					displayValue = "";
				}else{
					displayValue = $('#' + currentAttributes[i].id)[0].selectedOptions[0].text;
				}
				caseElements[index1].children[index2].data[i].displayValue = displayValue;
			}
		}
	}
	
};
// 封装条件组合
function packagingCondition() {
	// 封装条件组合数据 childrenAttrs数组
	var childrenAttrs = [];
	// 拿到所有name，灯，速度，压力
	var conditionsObj = $(".addCondition .curs");
	for (var b = 0; b < conditionsObj.length; b++) {// 灯，速度，压力
		var condition = $(conditionsObj[b]);
		var departmentId = condition.children(".department").children("option")
				.attr("id");// 拿到对应的id
		var id = condition.children(".condition").children("option").attr("id");// 拿到对应的id
		var conditionName = condition.children(".condition").children("option")
				.val();
		var script = condition.children(".condition").children("option").attr(
				"data");// 拿到对应的script
		var parentRelation = "";// 与上一个条件的关系
		if (condition.children(".andor").children("option").length != 0) {
			parentRelation = condition.children(".andor").children("option")
					.val();
		}
		;
		var relation = condition.children(".symbol").children("option").val();
		var value = "";
		var enters = condition.children(".enters");
		var displayName = "";
		if (enters) {
			if (enters[0].id !== "") {
				value = enters[0].id;
				displayName = enters[0].value;
			} else {// 输入框
				value = enters[0].value;
			}
		}
		childrenAttrs.push({
			departmentId : departmentId,// 系别id
			parentRelation : parentRelation,
			caseElementValId : caseElementValId,
			conditionId : id,
			conditionName : conditionName,
			displayName : displayName,
			value : value,
			relation : relation,
			sort : b + 1, // 条件组合排序
			script : script,
			parentId : 0
		});
	}
	return childrenAttrs;
}
// 获取当前点击位置信息
function getEventPosition(ev) {
	var x = 0;
	var y = 0;
	if (ev.layerX || ev.layerX == 0) {
		x = ev.layerX;
		y = ev.layerY;
	} else if (ev.offsetX || ev.offsetX == 0) { // Opera
		x = ev.offsetX;
		y = ev.offsetY;
	}
	return {
		x : x,
		y : y
	};
}
// 判断当前坐标位置是否存在元素,暂时只判子元素信息
function isExistElement(p, caseElements) {
	var cel = caseElements.length;
	var result = false;
	if (cel > 0) {
		for (var i = 0; i < cel; i++) {
			var cscl = caseElements[i].children.length;
			if (cscl > 0) {
				for (var j = 0; j < cscl; j++) {
					var element = caseElements[i].children[j];
					// 区域值宽110实际为90,区域值高40实际为30
					var x = element.x - 10;
					var y = element.y - 5;
					var width = element.width + 20;
					var height = element.hight+ 10;
					if (p.x >= x && p.y >= y && p.x <= (x + width)
							&& p.y <= y + height) {
						result = true;
						return result;
					}
				}
			}
		}
	}
	return result;
}
// 获取选中元素下标,修改选中元素的区域
function getSelectElements(caseElements) {
	var selection = [];
	if (caseElements) {
		for (var i = 0; i < caseElements.length; i++) {// 四个图形元素
			if (caseElements[i].isSelected == true) {// 被选中的元素
				selection.push(i);
				selectx1 = caseElements[i].x - 20;
				selectx2 = caseElements[i].x - 20 + caseElements[i].width;
			} else if (caseElements[i].isSelected == false
					&& caseElements[i].children != null
					&& caseElements[i].children.length !== 0) {
				var childrens = caseElements[i].children;
				for (var k = 0; k < childrens.length; k++) {
					if (childrens[k].isSelected == true) {
						selection.push(i);
						selection.push(k);// 选中的子元素
					}
				}
			}
		}
	}
	return selection;
}
// 在画布中拖动用例元素改变位置并重新绘画所有元素信息
function dragElement(e, caseElements, elementTypes) {
	// 鼠标当前所在的位置
	var x = e.offsetX;
	var y = e.offsetY;
	var p = {
		x : x,
		y : y
	};
	var px = 0;// 条件轴移动偏移量
	var selections = getSelectElements(caseElements);// 获取选中元素下标数组
	var selectElement = "";
	if (e.buttons == 1 && selections.length > 0) {// 鼠标按下且当前有选中元素将选中元素移动到鼠标位置
		// 拿到被拖动元素的下标
		var index1 = -1;
		var index2 = -1;
		if (selections.length > 1) {
			index1 = selections[0];
			index2 = selections[1];
			if (x >= selectx1 && (x + 45) <= selectx2
					&& !isExistElement(p, caseElements) && checkVCoor(p, caseElements,selections)) {// 元素只能在条件轴限定区域内移动且不能覆盖已存在元素
				caseElements[index1].children[index2].x = selectx1 + 90
						* Math.floor((x - selectx1) / 90) + 10;
				draw(e.target, elementTypes, caseElements);
				selectElement = caseElements[index1].children[index2];// 获取当前选中元素
				// 删除当前元素并重新添加进去，达到更新元素顺序的目的
				caseElements[index1].children.splice(index2, 1);
				// 更新之后元素顺序
				for (var j = index2; j < caseElements[index1].children.length; j++) {
					caseElements[index1].children[j].displayOrder = j + 1;
				}
				pushParentElement(selectElement, caseElements);
			}
		} else if (selections.length == 1) {
			index1 = selections[0];
			var selectArea = caseElements[index1].selectArea;
			if (x > 115 && x < canvase_width && selectArea != 0) {// 改变条件轴信号机等元素位置
				px = x - caseElements[index1].x +20;
				if (Math.abs(px) > 5) {// 防止频繁更新出现拖屏现象
					// 更新当前元素以及之后元素位置
					updatePosition(index1, px);
					draw(e.target, elementTypes, caseElements);
				}
			} else if (x > 115 && x < canvase_width && selectArea == 0) {// 改变条件轴限定区域
				var width = x - caseElements[index1].x;
				var minWidth = 90;//拓展条件轴右侧缩小条件轴区域时的最小值，不可把条件轴中的元素置到条件轴外面，条件轴的拖拽边界最小宽度=最后一个小矩形元素的x坐标+小矩形宽度+差值
				if(caseElements[index1].children.length>=1){
					minWidth = caseElements[index1].children[(caseElements[index1].children.length - 1)].x+caseElements[index1].children[(caseElements[index1].children.length - 1)].width-caseElements[index1].x+(90 - caseElements[index1].children[(caseElements[index1].children.length - 1)].width)/2;
				}
				
				if (width < minWidth) {
					width = Math.ceil(minWidth / 90) * 90;
				} else {
					width = Math.ceil(width / 90) * 90;
				}
				//扩大当前条件轴宽度时，如果右侧已经有条件轴，那么右侧的条件轴向右自动移动
				if(index1!=caseElements.length-1 &&currentWdith!=0 && currentWdith!=width&&currentWdith<width){
					// 更新当前元素以及之后元素位置
					updatePosition(index1+1, 90);
				}
				currentWdith = width;
				
				caseElements[index1].width = width;
				draw(e.target, elementTypes, caseElements);
			}
		}

	}
}
// 根据基本用例id获取当前基本用例的详细信息并在canvas内绘制显示
function getElementsByCaseId(id, canvas, elementTypes) {// 通过ID获得新增用例的数据
	// 根据用例ID获取用例元素属性信息
	$.ajax({
		url : '../../../basecase/getElementAndAtrributeByCaseId',//
		type : 'POST',
		data : {
			caseId : id
		},
		success : function(data) {
			if(data.flag==0){
				caseElements = data.content;
				draw(canvas, elementTypes, caseElements);// 获取点击的基本用例元素信息后重新绘制图形区域内容
				// 默认选中第一个条件轴元素并且更新元素移动区域selectX1
				if (caseElements.length > 0) {
					var p = {
							x : caseElements[0].x - 20,
							y : caseElements[0].y - 10
					};
					canvasClick(p, caseElements, elementTypes, canvas);
					getSelectElements(caseElements);
				}
				reDrawCheckPoint(caseElements, elementTypes, canvas);
				
				if(!firstGetCanvaseWidth && caseElements.length>0){
					firstGetCanvaseWidth = true;
					canvase_width = caseElements[caseElements.length - 1].x+caseElements[caseElements.length - 1].width+100;
					if(canvase_width<1500){
						canvase_width = 1500;
					}
					$("#canvasId").width(canvase_width);
					canvas.height=750;
					canvas.width=canvase_width;
					draw(canvas, elementTypes, caseElements);
				}
			}else{
				danger(data.errorInfo);
			}
		}
	});
}
function set_a_value(th) {// th this用来获取属性值，ys就是整个元素对象
	if(th.max){
		if(th.value ==''){
			console.log(th.attributes);
			var info = "<div style='color:black;'>输入值不能为空！</div>";
			if(th.attributes.currentValue){
				th.value = th.attributes.currentValue.value;
			}else if(th.attributes.min){
				th.value = th.attributes.min.value;
			}else{
				th.value = 0;
			}
			warning(info);
			return;
		}
		//当输入框的输入内容不在有效范围内，则提示重新输入
		if(Number(th.value)>Number(th.max) || Number(th.value) < Number(th.min)){
			var info = "<div style='color:black;'>请输入有效范围的数字:"+th.min+"-"+th.max+ "</div>";
			if(th.attributes.currentValue){
				th.value = th.attributes.currentValue.value;
			}else{
				th.value = 0;
			}
			warning(info);
	        return false;
		}
	}
	var ys = "";
	saves();
	var valss = th.value;
	var atrrCode = th.name;
	var id = $(th).parent().parent().prev().children().children(".backblock")
			.attr("id");
	for (var i = 0; i < caseElements.length; i++) {
		var children = caseElements[i].children;
		for (var k = 0; k < children.length; k++) {
			if (id == children[k].id) {
				ys = children[k];
			}
		}
	}
	var context = mycanvas.getContext('2d');
	if (valss !== undefined && ys !== "") {// 如果修改了值
		var data = ys.data;
		for (var i = 0; i < data.length; i++) {
			if ((ys.type == "004" && atrrCode == "004002002")
					|| ys.type == "004" && atrrCode == "004004001") {// 修改的是jtc信号
				ys.text = valss;// 改变后的值加入到元素中去
				var x = ys.x;
				var y = ys.y;
				var width = ys.width;
				var height = ys.hight;
				context.clearRect(x, y, width, height);// 清空需要更新数值的小矩形
				// redrawDiagonal(context,ys);//重绘元素小矩形的函数
				var rediagonal = tDrawCanvas.getDrawing('rediagonal', {
					obj : ys
				});
				rediagonal.draw();
				break;
			}
			if (ys.type == "007" && atrrCode == "007001003") {// 点击的元素是按键的时候
				ys.text = valss;// 改变后的值加入到元素中去
				var x = ys.x;
				var y = ys.y;
				var width = ys.width;
				var height = ys.hight;
				context.clearRect(x, y, width, height);// 清空需要更新数值的小矩形
				// redrawDiagonal(context,ys);//重绘元素小矩形的函数
				var rediagonal = tDrawCanvas.getDrawing('rediagonal', {
					obj : ys
				});
				rediagonal.draw();
				break;
			}
			if (ys.type == "010" && atrrCode == "010001001") {// 点击的元素是延时的时候
				var text = ys.text.substring(0, 2);
				ys.text = text + valss + "s";// 改变后的值加入到元素中去
				// 重新绘制元素矩形。精确到元素小矩形范围的清除和重绘
				// 计算清除的范围
				var x = ys.x;
				var y = ys.y;
				var width = ys.width;
				var height = ys.hight;
				context.clearRect(x, y, width, height);// 清空需要更新数值的小矩形
				// redrawDiagonal(context,ys);//重绘元素小矩形的函数
				var rediagonal = tDrawCanvas.getDrawing('rediagonal', {
					obj : ys
				});
				rediagonal.draw();
				break;
			}
		}

	}
	
	if(atrrCode == "011001007"){//信号机编号
		var isShow = false;
		if(valss!=""){
			isShow = true;
		}
		for (var i = 0; i < caseElements.length; i++) {
			var children = caseElements[i].data;
			for (var k = 0; k < children.length; k++) {
				if (th.id == children[k].id) {
					if(isShow){
						if(!caseElements[i].signalBool){
							caseElements[i].signalBool = true;
						}
					}else{
						if(caseElements[i].signalBool){
							caseElements[i].signalBool = false;
						}
					}
					caseElements[i].signalName = valss;
					var context = mycanvas.getContext('2d');
					context.clearRect(0, 0, canvase_width, mycanvas.height);
					contextCopy.clearRect(0, 0, mycanvasCopy.width, mycanvasCopy.height);
					draw(mycanvas, elementTypes, caseElements);
				}
			}
		}
	}
}
// 根据基本用例id从后台查询基本用例的基本信息
function getBaseCaseByCaseId(addBaseCaseId) {// 根据ID查到整个tr的信息
	$.ajax({
		url : '../../../basecase/queryBaseCaseList',
		type : 'POST',
		data : {
			pageSize : 10,
			pageNumber : 1,
			sortName : 'ID',
			sortOrder : 'desc',
			caseId : addBaseCaseId
		},
		success : function(data) {
			if (data.flag == "0") {
				baseCaseData = data.content.list;// 拿到新增用例的信息数据
			} else {
				return [];
			}
		},
		error : function() {
			return [];
		}
	});
}
// 手风琴效果
function accordion() {
	$("#accordionso").click(function() {
		$("#accordionso").css({
			"background-color" : "#337AB7",
			"color" : "white",
			"cursor":'default'
		});
		$("#accordionst").css({
			"background-color" : "#42464a",
			"color" : "#b4b2b2",
			"cursor":'pointer'
		});
		$("#basecase").css("display", "none");
		$("#easyui").css("display", "block");
		initButton(taskState);
		
		rightParameter();
	});
	$("#accordionst").click(function() {
		$("#accordionst").css({
			"background-color" : "#337AB7",
			"color" : "white",
			"cursor":'default'
		});
		$("#accordionso").css({
			"background-color" : "#42464a",
			"color" : "#b4b2b2",
			"cursor":'pointer'
		});
		$("#easyui").css("display", "none");
		$("#basecase").css("display", "block");
		
		rightParameter();
	});
}

function initButton(status) {
	baseCaseEditeBool = false;
	if (roleButton().indexOf("jbylsh") != -1 && status == 1) {// 基本用例为提交未审核才展示审核按钮
		$('#Audit').removeAttr("hidden");
		$('#edite').attr("hidden",'hidden');
		$('#submit').attr("hidden",'hidden');
		$('#emptyElements').attr("hidden",'hidden');
		$('#deleteElements').attr("hidden",'hidden');
	}
	if (roleButton().indexOf("jbylbj") != -1 && status == 0 || status == 3) {// 基本用例为未提交才展示保存，提交等按钮
		$('#Audit').attr("hidden",'hidden');
		$('#edite').removeAttr("hidden");
		$('#submit').removeAttr("hidden");
		$('#emptyElements').removeAttr("hidden");
		$('#deleteElements').removeAttr("hidden");
		baseCaseEditeBool = true;
	}
	
	if (roleButton().indexOf("jbylsh") != -1 && status == 2) {// 基本用例为提交未审核才展示审核按钮
		$('#Audit').attr("hidden",'hidden');
		$('#edite').attr("hidden",'hidden');
		$('#submit').attr("hidden",'hidden');
		$('#emptyElements').attr("hidden",'hidden');
		$('#deleteElements').attr("hidden",'hidden');
	}
}
function rightParameter() {// 根据用户权限判断让右侧的参数修改和不可修改
	if ($("#edite").attr("hidden") == undefined) {// 有权限时功能可用
		$("#elementContents .conditionTemplate select").removeAttr("disabled");
		$("#elementContents .conditionTemplate input").removeAttr("readOnly");
		
		$("#externalParameter select").removeAttr("disabled");
		$("#externalParameter input").removeAttr("readOnly");
	} else {// 没有权限时，按钮禁用，功能隐藏
		$("#elementContents input").attr("readOnly", "true");
		$("#elementContents select").attr("disabled", "disabled");
		
		$("#externalParameter input").attr("readOnly", "true");
		$("#externalParameter select").attr("disabled", "disabled");
	}
}

//复制元素到指定坐标
function copyElement(p, caseElements, elementTypes){
	if(!copyObj || copyObj.length<=0){
		return;
	}
	var x = p.x;
    var y = p.x; 
      var elementId = copyObj[0].elementId;
      var type = copyObj[0].type;
      var leve =  copyObj[0].leve;
      var elementType = getElementType(type,elementTypes);
      if(leve=="1"){//元素大类1：基本元素，
        x=selectx1+90*Math.floor((x-selectx1)/90)+10;
        y=elementType.y1+5;//图形放下后的位置进行调整
      }else if(leve=="3"){//元素大类3图形元素
          y = 660;
      }
      getCopyCaseElementInstance(currentCanvas,elementId,x,y,caseElements,elementTypes);//绘制元素和图形的方法
      
      //复制对象的子元素
      if(copyObj[0].children && copyObj[0].children.length>0){
    	  cellIndex = 0;
    	  clickBool = false;
    	  for(var i = 0;i<copyObj[0].children.length;i++){
    		//复制条件轴的时候元素一个一个的显示出来
    		 if(copyObj[0].children.length<8){//元素个数不同，时间间隔不一样
    			 setTimeout(drawSmallCellFun,200*i);
    		 }else{
    			 setTimeout(drawSmallCellFun,600*i);
    		 }
          }
      }
}

//复制条件轴的时候元素一个一个的显示出来
var cellIndex = 0;
function drawSmallCellFun(){
	 copyElementCell(copyObj[0].children[cellIndex],{x:(copyObj[0].children[cellIndex].x - copyObj[0].x+caseElements[caseElements.length-1].x),y:copyObj[0].children[cellIndex].y}, caseElements, elementTypes);
	 if(cellIndex>=copyObj[0].children.length-1){
		  clickBool = true;
	  }
	 cellIndex++;
}
//复制对象的子元素
function copyElementCell(obj,p, caseElements, elementTypes){
	if(!copyObj || copyObj.length<=0){
		return;
	}
	var x = p.x;
    var y = p.y; 
      var elementId = obj.elementId;
      var type = obj.type;
      var leve =  obj.leve;
      var elementType = getElementType(type,elementTypes);
      if(leve=="1"){//元素大类1：基本元素，
        y=elementType.y1+5;//图形放下后的位置进行调整
      }else if(leve=="3"){//元素大类3图形元素
          y = 660;
      }
      getCopyCaseElementInstance(currentCanvas,elementId,x,y,caseElements,elementTypes,obj);//绘制元素和图形的方法
}
//根据元素ID和当前位置信息,生成元素信息，然后在画布上绘画此元素，并将此元素信息添加到全局变量中，并返回此对象
function getCopyCaseElementInstance(mycanvas, elementId, x, y, caseElements,
		elementTypes,cellObj) {
	$.ajax({
		type : "POST",
		url : "../../../basecase/getCaseElement",
		data : {
			elementId : elementId,
			x : x,
			y : y
		},
		dataType : "json",
		async : false,
		success : function(data) {
			var obj = data.content;// 新生成的图形元素的数据
			if (obj != null && obj != undefined) {
				var p = {
					x : 0,
					y : 0
				};
				//复制上个控件的元素信息
				obj.data = [];
				obj.data = [].concat(JSON.parse(JSON.stringify(copyObj[0].data)));
				if (obj.leve == 1) { // 通过leve（大类）进行判断是否画矩形
					p = {
						x : x + 5,
						y : y + 5
					};
					//复制上个控件的元素信息
					if(cellObj && cellObj.data){//此时是复制条件轴，条件轴中包括小矩形
						obj.data = [];
						obj.data = [].concat(JSON.parse(JSON.stringify(cellObj.data)));
					}
					if(obj.name == "010001"){//延时
						if(obj.data[0].value){
							obj.text = "延时"+obj.data[0].value+"s";
						}else{
							obj.text = "延时5s";
						}
					}
					
					//设置按键输入，jtc信号，平调信号的默认显示和默认值
					var index = 0;
					if(obj.name == "004002" || obj.name == "007001"){
						index = 1;
					}else if(obj.name == "004004"){
						index = 0;
					}
					if(obj.name == "004002" || obj.name == "007001" ||obj.name == "004004"){
						var valueId = obj.data[index].dic[0].id;
						if(obj.data[index].value){
							valueId = obj.data[index].value;
						}	
						for(var n =0;n<obj.data[index].dic.length;n++){
							if(obj.data[index].dic[n].id == valueId){
								obj.text = obj.data[index].dic[n].name;
								obj.data[index].value = obj.data[index].dic[n].id;
								break;
							}
						}
					}
					
					var diagonal = tDrawCanvas.getDrawing('diagonal', {
						obj : obj
					});
					diagonal.draw();
					// 根据obj位置信息判断当前节点的父节点并将其加入其中
					caseElements = pushParentElement(obj, caseElements);
				} else if (obj.leve == 3) {
					var type = obj.type;
					obj.children = [];// 存放条件轴内元素的数组
					obj.parentId = 0;// 后台区分数据用的参数
					if (type == "011") {
						// 画条件轴
						p = {
							x : x - 20,
							y : y - 5
						};
						obj.width = copyObj[0].width;// 矩形的默认宽度
						var conditionArea = tDrawCanvas.getDrawing(
								'conditionArea', {
									obj : obj,
									elementTypes : elementTypes
								});
						conditionArea.draw();
						caseElements = pushParentElement(obj, caseElements);
					} else if (type == "012") {
						p = {
							x : x,
							y : y - 65
						};
						var signal = tDrawCanvas.getDrawing('signal', {
							obj : obj
						});
						signal.draw();
						caseElements = pushParentElement(obj, caseElements);
					} else if (type == "013") {
						var graph = tDrawCanvas.getDrawing('graph');
						graph.draw();
					} else if (type == "014") {
						p = {
							x : x,
							y : y - 65
						};
						var kvalueMap = tDrawCanvas.getDrawing('kvalueMap', {
							obj : obj
						});
						kvalueMap.draw();
						caseElements = pushParentElement(obj, caseElements);
					}
				}
				canvasClick(p, caseElements, elementTypes, mycanvas);
			}
			return caseElements;
		}
	});
}

//判断当前坐标是否可以粘贴
function canPaste(){
	var x = copyObjPostion.x;
	var y = copyObjPostion.y;
	var p = {
		x : x,
		y : y
	}; 
    var type = copyObj[0].type;
    var leve =  copyObj[0].leve;
	var dragable = false;
	var maxY = elementTypes[elementTypes.length - 1].y2 + 10;
	if (leve == "1") {
		if (x >= selectx1 && x <= selectx2 && y >= 110 && y <= maxY) {
			for (var i = 0; i < elementTypes.length; i++) {
				// 判断拖拽的图形元素是否在其类型的区域内与条件轴限定区域内
				if (elementTypes[i].name == type && y > elementTypes[i].y1
						&& y < elementTypes[i].y2) {
					if (!isExistElement(p, caseElements)) {
						dragable = true;
					}
				}
			}
		}
	} else if (leve == "3") {// 判断图形元素的绘制区域
		if (y > maxY) {// 得到限定是画直线还是画图形的Y值(最后一条直线的Y)
			dragable = true;
		}
	}
	return dragable;
}

//Ctrl+c ctrl+v 快捷键复制粘贴功能
function keydown(e){
	if(!baseCaseEditeBool){
		return;
	}
	if(event.ctrlKey == 1) {
		if(document.all) {
			k = e.keyCod;
		} else {
			k = e.which;
		}
		if(k == 86) {//粘贴
			if(!baseCaseEditeBool){
				danger("当前不可复制粘贴！");
				return;
			}
			if(!clickBool){
				danger("控件还未复制完成！");
				return;
			}
			if(copyObj[0].leve == '1'){
				if(canPaste()){
					copyElement(copyObjPostion, caseElements, elementTypes);
					book("粘贴成功！");
				}else{
					danger("当前条件轴未被选定或者此控件不能粘贴到此处！");
				}
			}else if(copyObj[0].leve == '3'){
				if(copyObjPostion.x-15<(caseElements[caseElements.length - 1].x + caseElements[caseElements.length - 1].width)){
					danger("此控件不能粘贴到此处！");
				}else{
					copyElement(copyObjPostion, caseElements, elementTypes);
					book("粘贴成功！");
				}
			}
		}
		if(k == 67) {//复制
			if(!baseCaseEditeBool){
				danger("当前不可复制粘贴！");
				return;
			}
			if(!clickBool){
				danger("控件还未复制完成！");
				return;
			}
			copyObj = [];
			copyObj.push(selectObj[0]);//点击的元素对象
			book("复制成功！");
		}
	}
	
	if(e.code == 'Delete'){//删除键点击
		if(!baseCaseEditeBool){
			danger("当前不可编辑！");
			return;
		}
		book("删除成功！");
		deleteElements(currentCanvas, caseElements);
	}
}
//基本用例中的快捷键复制粘贴和删除添加成功提示
function book(str){
	$('#alertText').html(str);
    $('#myModal').modal('show');
    setTimeout(function(){
        $("#myModal").modal("hide");
    },1200);
}

//删除元素或者清空元素后，重置右侧的控件信息
function resetMsg(){
	$("#caseNamee").empty();
	$("#elementContents").empty();
	$('#conDescription').empty(); // 清空控件说明描述内容
	$('#outParameter').empty();// 清空外部参数内容
}

//拖拽元素时，判断是否超出对应控件类型的纵坐标范围
function checkVCoor(p, caseElements,selections){
	var elementType = getElementType(caseElements[selections[0]].children[selections[1]].type,elementTypes);
	var result = false;
	if(p.y> elementType.y1&&p.y<elementType.y2){
		result = true;
	}
	return result;
}
//当条件数》=1时，则关系比不能为空
function updateRelationData()
{
	if($('#elementContents').find('.addCondition').length!=0){
		$('.conditionsTemplate').find('.andor').empty();
		$('.conditionsTemplate').find('.andor').append("<option>and</option><option>or</option>");
		andorVal='and';
	}else{
		$('.conditionsTemplate').find('.andor').empty();
		$('.conditionsTemplate').find('.andor').append("<option></option>");
		andorVal='';
	}
}

//右键添加条件轴时对其他条件轴的位置调整
function setNewConditionPosition(type){
	var selections = getSelectElements(caseElements);// 获取选中元素下标数组
	if (selections.length == 1) {
		index1 = selections[0];
		// 更新当前元素以及之后元素位置
        if(type == 0){//0：左侧添加，1：右侧添加
        	updatePosition(index1, 50+90);
    		x = caseElements[index1].x-50-90;
        }else{
        	updatePosition(index1+1, 50+caseElements[index1].width);
    		x = caseElements[index1].x+caseElements[index1].width+50;
        }
        y = 660;
        getCaseElementInstance(mycanvas,'24',x,y,caseElements,elementTypes);//绘制元素和图形的方法
        draw(mycanvas, elementTypes, caseElements);
	}
}

//条件轴内的小矩形右键添加一列
function setNewRowPosition(type,selection,selectionLocation){
	var conditionIndex = selectionLocation[0];//当前条件轴索引
	//扩大当前条件轴宽度时，如果右侧已经有条件轴，那么右侧的条件轴向右自动移动
	if(conditionIndex!=caseElements.length-1){
		// 更新当前元素以及之后元素位置
		updatePosition(conditionIndex+1, 90);
	}
	caseElements[conditionIndex].width = caseElements[conditionIndex].width+90;
	var currentX = selection[0].x;
	if(type == 0){//左侧加一列
		for(var i = 0;i<caseElements[conditionIndex].children.length;i++){
			var child = caseElements[conditionIndex].children[i];
			if(child.x>=currentX){
				child.x = child.x + 90;
			}
		}
	}else{//右侧加一列
		currentX = caseElements[conditionIndex].children[selectionLocation[1]].x;
		for(var j = selectionLocation[1];j<caseElements[conditionIndex].children.length;j++){
			if(caseElements[conditionIndex].children[j].x!=currentX){
				var child2 = caseElements[conditionIndex].children[j];
				child2.x = child2.x + 90;
			}
		}
	}
	
	draw(mycanvas, elementTypes, caseElements);
}


function formatDateTime(inputTime) {  
    var date = new Date(inputTime);
    var y = date.getFullYear();  
    var m = date.getMonth() + 1;  
    m = m < 10 ? ('0' + m) : m;  
    var d = date.getDate();  
    d = d < 10 ? ('0' + d) : d;  
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;  
    second = second < 10 ? ('0' + second) : second; 
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;  
}

//时间格式校验
function checkDateTime(date){
      var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
      var r = date.match(reg);
      if(r != null || date == '-1'){
          return true;
      }else{
    	  warning("输入格式不正确，请按yyyy-MM-dd HH:mm:ss的格式输入！");
    	  return false;
      }        
 }